﻿Imports System.IO
Imports System.Reflection
Imports System.Linq
Imports System.Xml.Linq
Imports System.Environment
Imports System.Windows.Forms.Application
Imports System.Text.RegularExpressions
Imports System.Data.SQLite
Imports Link.AppShortcut
Imports Link.InternetShortcut
Imports System.Runtime.CompilerServices
Imports System.ComponentModel
Imports System.Drawing.Imaging


Module StringExtensions
    <Extension()>
    Public Function Contains(str As String, substring As String,
                            comp As StringComparison) As Boolean
        If substring Is Nothing Then
            Throw New ArgumentNullException("substring",
                                            "substring cannot be null.")
        ElseIf Not [Enum].IsDefined(GetType(StringComparison), comp) Then
            Throw New ArgumentException("comp is not a member of StringComparison",
                                        "comp")
        End If
        Return str.IndexOf(substring, comp) >= 0
    End Function
End Module

Public Class GameSetMatch

    'CONSTANTS
    Public _KeepDSFile As String = Environment.GetFolderPath(SpecialFolder.ApplicationData) & "\GameSetMatch\GameSetMatch.xml"
    Public _LogFile As String = Environment.GetFolderPath(SpecialFolder.ApplicationData) & "\GameSetMatch\GameSetMatch.log"
    Public Version = "1.3.1"

    'WEBBROWSER
    Public _ImgSearchDDEnum = New List(Of String) From {"", "Logo", "Fanart", "Background", "Wallpaper", "Advert", "Box", "Title", "Screenshot", "Character", "Marquee", "Banner"}
    Public _ImgSearchSizeDic = New Dictionary(Of String, String)
    Public _ImgSearchColorDic = New Dictionary(Of String, String)
    Public _ImgSearchTypeDic = New Dictionary(Of String, String)
    Public _ImgSearchFormatDic = New Dictionary(Of String, String)
    Public hecImages As HtmlElementCollection
    Public Shared StoredImage As Image
    Public Shared StoredImgPath As String

    'PUBLIC VARS
    Public _ListDataset As New DataSet

    Public _Listxml As New XMLOps

    Public _NewItemsFolder As String = My.Settings.FPNew
    Public _LocalItemsFolder As String = My.Settings.FPLocal
    Public _CloudSyncFolder As String = My.Settings.FPCloud
    Public _ResizeFolder As String = "C:"
    Public _ListFilepath As String = My.Settings.FPDat

    Public _FileParser As New FileParse
    Public _ImgExts As String = My.Settings.ImageExts

    Public _MainDT As New DataTable
    Public _Missing As New DataTable
    Public NewImgPrev As New Preview

    Public GamesLoaded As Boolean = False

    Public SystemDatDict As New Dictionary(Of String, List(Of String))


    'HIGHLIGHTING + FILETERING
    Public F1Col As Integer = 4 'Column to Use as comparitor in 1st folder
    Public F2Col As Integer = 15 'Column to Use as comparitor in 2nd folder
    Public HLOprtr As String = "GTT"
    Public HighlighCol As Color = My.Settings.HighlightCol
    Public Filtered As Boolean = False
    Public DGVRedrawFlag As Boolean = False

    Public TopSelectedRow As Integer
    Public LastRelSort As System.ComponentModel.ListSortDirection = System.ComponentModel.ListSortDirection.Ascending

    'Log
    Public log As New Logger

    'FuzzySearch
    Public FSearchActive As Boolean = False

    Public formloaded As Boolean = False
    Public DatabaseChanged As Boolean = False


    ' =========================================================
    ' Dictionarys etc
    ' =========================================================

    Private Sub SetupSysDat()
        SystemDatDict.Add("MAME", New List(Of String)(New String() {"One", "Two", "Three"}))
        SystemDatDict.Add("GameEx", New List(Of String)(New String() {"Name", "MAME", "GameBase", "HyperList", "GoodName", "NoIntro", "TOSEC", "ReDump"}))
        SystemDatDict.Add("HyperList", New List(Of String)(New String() {"Name", "Description"}))
    End Sub

    'Private Sub GameSetMatch_GotFocus(sender As Object, e As EventArgs) Handles Me.Activated
    '    If formloaded = True Then
    '        MsgBox("got foussc")
    '        RefreshImgBT_Click(Nothing, Nothing)
    '    End If


    'End Sub

    ' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    '                 MAIN LOAD
    ' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


    Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Me.Font = My.Settings.UIFont
        Me.Location = My.Settings.WindowPos
        Me.Size = My.Settings.WindowSize
        Me.WindowState = My.Settings.WindowState
        Me.DoubleBuffered = True

        TestWorkingDir()
        '   ShortcutsToProgramFolder()

        SetupApp()

        'loggin enabled hereafter

        SetupForm()


        'On initial load - disable other tabs as no data loaded:
        TabControl1.TabPages(1).Enabled = False

        log.Log_Data("App loaded..")

        formloaded = True

    End Sub

    Private Function DBBackup() As Boolean
        Dim DBBU As New BackupRoller
        With DBBU
            .BackupDirectory = Environment.GetFolderPath(SpecialFolder.ApplicationData) & "\GameSetMatch\DbBackup"
            .BackupFile = Environment.GetFolderPath(SpecialFolder.ApplicationData) & "\GameSetMatch\GameSetMatch.xml"
            .KeepDays = New List(Of DayOfWeek) From {DayOfWeek.Saturday, DayOfWeek.Wednesday}
            .KeepDaysNumber = 2
            .KeepDates = New List(Of Day) From {14, 26}
            .KeepDatesNumber = 1
            .KeepTodayNumber = 10
            .KeepYesterday = True
            .YesterdayNumber = 5
            .Oldest = 6
        End With
        DBBU.Initialise()
        If DBBU.Backup() = False Then
            Return False
        Else
            Return True
        End If
    End Function

    Sub TestWorkingDir()
        If Not My.Computer.FileSystem.DirectoryExists(Environment.GetFolderPath(SpecialFolder.ApplicationData) & "\GameSetMatch") Then
            My.Computer.FileSystem.CreateDirectory(Environment.GetFolderPath(SpecialFolder.ApplicationData) & "\GameSetMatch")
        End If

        If Not Directory.Exists(Environment.GetFolderPath(SpecialFolder.ApplicationData) & "\GameSetMatch\DbBackup") Then
            Directory.CreateDirectory(Environment.GetFolderPath(SpecialFolder.ApplicationData) & "\GameSetMatch\DbBackup")
        End If

    End Sub

    Sub ShortcutsToProgramFolder()
        Dim file_dir As String = "GameSetAndMatch"
        Dim file_name As String = "LogFile"
        Dim full_path As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), file_dir, file_name)
        Debug.WriteLine(full_path & vbCr & My.Resources._256x256_ios7_folder_icon.ToString & vbCr & Environment.GetFolderPath(Environment.SpecialFolder.Programs))
        If IO.File.Exists(full_path) Then
            Debug.WriteLine("The file already exist.")
        Else
            Debug.WriteLine("The file NOT exist.")
            'create shortcuts
            Dim szName As String = "LogFile"
            Dim szTagetFile As String = Environment.GetFolderPath(SpecialFolder.ApplicationData) & "\GameSetMatch\GameSetMatch.log"
            Dim szWorkingDir As String = Path.GetTempPath
            Dim szCmdLine As String = "" '(Optional) If your application have cmd line
            'and you want to run with cmd line add here  "-cmdline" or "/cmdline".
            Dim szComment As String = "" '(Optional) Description of shortcut.
            ' Dim szIcon As String = Application.StartupPath() = + 
            Dim nIndex As Integer = 0 'Default index is 0
            Dim WinStyle As ProcessWindowStyle = ProcessWindowStyle.Normal
            ' Dim szTarget As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs)).ToString
            ' Dim szTarget As String = Target(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs)))
            ' Dim szCustomPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
            Dim szTarget As String = "C:\Users\Steve\AppData\Roaming\Microsoft\Windows\Start Menu\Programs"
            'This option is to create folder in start menu.
            'When you choose Start Menu path, write your product name or company name for example,
            'and the folder will be created automatically.
            'You will find the shortcut inside of "Project Demo" folder.
            Dim szCreateDirForStartMenu As String = "Project Demo"

            AddLnkShortcut(szName, szTagetFile, szWorkingDir, szCmdLine, _
                                   szComment, Nothing, 0, WinStyle, szTarget, szCreateDirForStartMenu)


            ' IO.File.Create(full_path)
        End If

    End Sub

    Sub KeyPressMap(sender As Object, e As KeyEventArgs) Handles DGV1.KeyDown

        If e.KeyCode = Keys.W Then
            SendKeys.Send("{Up}")
            Debug.WriteLine("Kere")
        End If
        If e.KeyCode = Keys.A Then
            SendKeys.Send("{Left}")
            Debug.WriteLine("Kere")
        End If
        If e.KeyCode = Keys.S Then
            SendKeys.Send("{Down}")
            Debug.WriteLine("Kere")
        End If
        If e.KeyCode = Keys.D Then
            SendKeys.Send("{Right}")
            Debug.WriteLine("Kere")
        End If

        If e.KeyCode = Keys.Q Then
            NewPB_Click(NewPB, Nothing)
        End If

        If e.KeyCode = Keys.E Then
            If DGV1.CurrentRow.Cells("Sel").Value = False Then
                DGV1.CurrentRow.Cells("Sel").Value = True
            Else
                DGV1.CurrentRow.Cells("Sel").Value = False
            End If
        End If


    End Sub

    Private Sub GameSetMatch_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
        If DatabaseChanged = False Then
            SaveDataset()
        End If


        My.Settings.WindowPos = Me.Location
        My.Settings.WindowSize = Me.Size
        My.Settings.WindowState = Me.WindowState
        My.Settings.SplitPanel2Width = MainDGVSplit.SplitterDistance
        My.Settings.Save()

        log.Log_Data("Cheerio", "App closing")
    End Sub

    Sub LoadDataset()
        Debug.WriteLine("Load Dataset: " & _KeepDSFile)
        log.Log_Data("Loading dataset")
        If File.Exists(_KeepDSFile) Then
            Dim ImportData As New XMLOps
            With ImportData
                .Filepath = _KeepDSFile
                .Dataset = _KeepDS
            End With
            ImportData.ImportXML()
            log.Log_Data("Dataset successfully loaded.")
        Else
            log.Log_Error("GSM Dataset file not in directory. Check: " & _KeepDSFile, "DB Load")
        End If

        log.Log_Data("Backing up database xml...")
        If DBBackup() Then
            log.Log_Data("Database xml backed up successfully")
        Else
            log.Log_Error("Failiur during database xml backup")
        End If

    End Sub

    Sub SaveDataset()
        Dim ExportData As New XMLOps
        With ExportData
            .Filepath = _KeepDSFile
            .Dataset = _KeepDS
        End With
        ExportData.ExportXML()
    End Sub

    Sub SetupApp()

        log.Initialize("GameSetMatch", Version, _LogFile, True)
        LoadDataset()
        log.Log_Data("Dataset loaded")

    End Sub

    Sub SetupForm()

        Call PopDefaultSetup()

        'System DATS data:
        SetupSysDat()

        GameColumnTB.Text = ""

        'System DATS box
        SystemsCB.Items.AddRange(SystemDatDict.Keys.ToArray)

        Dim DefaultSetup As Integer = -1
        For Each row As DataRow In _KeepDS.Tables("Setups").Rows
            SetupCB.Items.Add(row.Item("Name"))
            If row.Item("Startup") = True Then
                DefaultSetup = row.Item("ID")
            End If
        Next
        If DefaultSetup <> -1 Then
            PopulateSetup(DefaultSetup)
        End If

        'Settings

        SettsPrevH.Text = My.Settings.PrevH
        SettsPrevW.Text = My.Settings.PrevW
        SettsImgLayCB.Text = My.Settings.PrevLayout
        SettsWinStateCB.Checked = My.Settings.PrevWinState
        SettsBUOWsCB.Checked = My.Settings.BackupOWs
        SettsKeepLastCB.Checked = My.Settings.JustKeepLast
        SettsVerLB.Text = "Ver: " & Version
        SettsIncUmtchdCB.Checked = My.Settings.InclUnmatched
        MiniInfoTB.Text = My.Settings.MiniInfoT
        ListsDirTB.Text = CompactString(My.Settings.ListDir, ListsDirTB.Width, ListsDirTB.Font, TextFormatFlags.PathEllipsis)
        HLColPB.BackColor = My.Settings.HighlightCol
        KillBatch.Checked = My.Settings.KillBatch
        MatchRemBracketsChB.Checked = My.Settings.MatchRemBrackets
        SaveAsCB.Text = My.Settings.FileUseDBName
        RemBracksDBFilenameChB.Checked = My.Settings.RemBracksFilename
        RemBracksDBGamenameChB.Checked = My.Settings.RemBracksGamename
        IncImgsMatchGnChB.Checked = My.Settings.IncImgsMatchGN
        SaveAsPNGChB.Checked = My.Settings.SaveAsPng
        DefImageEditorTB.Text = My.Settings.DefImageEditor

        'SettsVerLB.Text = ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString

        'PostFont Text ops
        CompareCloudLB.Font = New Font(CompareCloudLB.Font, FontStyle.Bold)
        CompareLocalLB.Font = New Font(CompareLocalLB.Font, FontStyle.Bold)
        CompareNewLB.Font = New Font(CompareNewLB.Font, FontStyle.Bold)

        'Split panel
        MainDGVSplit.SplitterDistance = My.Settings.SplitPanel2Width

        'Comparitor CB setup
        Dim items(Me.ImageList1.Images.Count - 1) As String
        'For i As Int32 = 0 To Me.ImageList1.Images.Count - 1
        '    items(i) = "Item " & i.ToString
        'Next
        items(0) = "EQU"
        items(1) = "GEQ"
        items(2) = "LEQ"
        items(3) = "GTT"
        items(4) = "LST"
        items(5) = "NEQ"

        ComparitorFoldersCB.SelectedIndex = 0
        If My.Settings.HIghlight = False Then
            HighlightBT.BackColor = DefaultBackColor
        Else
            HighlightBT.BackColor = Color.Orange
        End If


        Me.ComparitorCB.Items.AddRange(items)
        Me.ComparitorCB.DropDownStyle = ComboBoxStyle.DropDownList
        Me.ComparitorCB.DrawMode = DrawMode.OwnerDrawVariable
        Me.ComparitorCB.ItemHeight = Me.ImageList1.ImageSize.Height
        Me.ComparitorCB.Width = Me.ImageList1.ImageSize.Width + 25
        Me.ComparitorCB.MaxDropDownItems = Me.ImageList1.Images.Count
        Me.ComparitorCB.SelectedIndex = 3

        'Copmparitor field
        ComparitorFieldCB.SelectedIndex = 0

        'DragDrop setup
        CompareNewGB.AllowDrop = True
        NewPB.AllowDrop = True
        ' AddHandler NewPB.DragEnter, AddressOf PBDragEnter

        'SEUP FUZZY MATCH DROPDOWN
        Dim comboSource As New Dictionary(Of String, String)()
        comboSource.Add("1", "Gray")
        comboSource.Add("2", "Blue")
        comboSource.Add("3", "Green")
        FuzzyFolderCB.DataSource = New BindingSource(comboSource, Nothing)
        FuzzyFolderCB.DisplayMember = "Value"
        FuzzyFolderCB.ValueMember = "Key"

        WebPanel.Hide()
        SearchTypeTG.Tag = "folder"

        'DATAGRID
        SetupDGVs()


        'setup WebBroswer Form
        SetupBrowserSearch()

        GameSearchTB.Font = New Font(My.Settings.UIFont.FontFamily, My.Settings.UIFont.Size, FontStyle.Bold)

        DefImageEditorTB.Select(DefImageEditorTB.Text.Length, 0)

        SourceFolderIconPB.Parent = FuzzyImagePB
        SourceFolderIconPB.Location = New Point(2, 2)

        log.Log_Data("Form setup")

    End Sub

    Private Sub SetupBrowserSearch()

        ' IMAGE SEARCH DROP DOWNS
        'Size
        _ImgSearchSizeDic.add("Any Size", "")
        _ImgSearchSizeDic.add("Large", "isz:l")
        _ImgSearchSizeDic.add("Medium", "isz:m")
        _ImgSearchSizeDic.add("400×300", "isz:lt,islt:qsvga")
        _ImgSearchSizeDic.add("640×480", "isz:lt,islt:vga")
        _ImgSearchSizeDic.add("800x600", "isz:lt,islt:svga")
        _ImgSearchSizeDic.add("1024×768", "isz:lt,islt:xga")
        _ImgSearchSizeDic.add(">1600×1200", "isz:lt,islt:2mp")
        _ImgSearchSizeDic.add(">2272×1704", "isz:lt,islt:4mp")

        'Color
        _ImgSearchColorDic.add("Full Color", "ic:color")
        _ImgSearchColorDic.add("Black and White", "ic:gray")
        _ImgSearchColorDic.add("Transparent", "ic:trans")

        'Type
        _ImgSearchTypeDic.add("Any Type", "")
        _ImgSearchTypeDic.add("Face", "itp:face")
        _ImgSearchTypeDic.add("Photo", "itp:photo")
        _ImgSearchTypeDic.add("Clip Art", "itp:clipart")
        _ImgSearchTypeDic.add("Line Drawing", "itp:lineart")
        _ImgSearchTypeDic.add("Animation", "itp:animated")

        'Format
        _ImgSearchFormatDic.add("Any Format", "")
        _ImgSearchFormatDic.add("PNG", "ift:png")
        _ImgSearchFormatDic.add("JPG", "ift:jpg")
        _ImgSearchFormatDic.add("GIF", "ift:gif")
        _ImgSearchFormatDic.add("SVG", "ift:svg")

        With ImgSearchTermCB
            .DataSource = _ImgSearchDDEnum
            .DropDownStyle = ComboBoxStyle.DropDownList
        End With

        With ImgSearchSizeCB
            .DataSource = New BindingSource(_ImgSearchSizeDic, Nothing)
            .DisplayMember = "Key"
            .ValueMember = "Value"
            .DropDownStyle = ComboBoxStyle.DropDownList
        End With

        With ImgSearchColorCB
            .DataSource = New BindingSource(_ImgSearchColorDic, Nothing)
            .DisplayMember = "Key"
            .ValueMember = "Value"
            .DropDownStyle = ComboBoxStyle.DropDownList
        End With

        With ImgSearchTypeCB
            .DataSource = New BindingSource(_ImgSearchTypeDic, Nothing)
            .DisplayMember = "Key"
            .ValueMember = "Value"
            .DropDownStyle = ComboBoxStyle.DropDownList
        End With

        With ImgSearchFormatCB
            .DataSource = New BindingSource(_ImgSearchFormatDic, Nothing)
            .DisplayMember = "Key"
            .ValueMember = "Value"
            .DropDownStyle = ComboBoxStyle.DropDownList
        End With


    End Sub

    Private Sub SetupDGVs()
        With FuzzyDGV
            .DataSource = _GSMDS.Tables("Matches")

            For Each col As DataGridViewColumn In FuzzyDGV.Columns
                If col.Name = "MatchOnFilename" Then
                    col.HeaderText = "File"

                ElseIf col.Name = "MatchOnGamename" Then
                    col.HeaderText = "Name"

                ElseIf col.Name = "ImgFilename" Then
                    col.DisplayIndex = 0
                Else
                    col.Visible = False
                End If

            Next

        End With


    End Sub

    '=====================================================================================================
    'TODO
    Private Sub PBDragEnter(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles NewPB.DragEnter
        Debug.WriteLine("Drag Enter")
        If e.Data.GetDataPresent(DataFormats.Bitmap) Then
            e.Effect = DragDropEffects.Copy
        End If

        '   Cursor.Current = Cursors.Hand
    End Sub

    Private Sub PBDragHover(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles NewPB.DragOver
        Debug.WriteLine("Drag Over")
        '  Cursor.Current = Cursors.Hand
    End Sub

    Private Sub PBDragLeave(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles NewPB.DragLeave
        Debug.WriteLine("Drag Leave")
        ' Me.Cursor = Cursors.Default
    End Sub

    Private Sub PBDragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles NewPB.DragDrop
        Debug.WriteLine("Drag drop")
        MsgBox(sender.ToString)
    End Sub

    Private Sub Me_GiveFeedback(ByVal sender As Object, ByVal e As GiveFeedbackEventArgs) Handles Me.GiveFeedback
        e.UseDefaultCursors = False
        Cursor.Current = Cursors.Cross
    End Sub

    Private Sub PBDrag_GiveFeedback(ByVal sender As Object, ByVal e As GiveFeedbackEventArgs) Handles NewPB.GiveFeedback
        e.UseDefaultCursors = False '3
        Cursor.Current = Cursors.SizeNESW
    End Sub

    '======================================================================================================




    Private Sub PopDefaultSetup()
        ''Temp
        NewTB.Text = "New Folder"
        LocalTB.Text = "Local Folder"
        CloudTB.Text = "Cloud Folder"
        ResizeTB.Text = ""
        DatTB.Text = "Game Data"

        FPNew.Text = ""
        FPLocal.Text = ""
        FPCloud.Text = ""
        FPResize.Text = ""
        FPDat.Text = ""

        GameColumnTB.Text = ""

        FPNew.Tag = ""
        FPLocal.Tag = ""
        FPCloud.Tag = ""
        FPResize.Tag = ""
        FPDat.Tag = ""

        SystemsCB.Text = "MAME"
        SetupCB.Text = ""
        DefaultChB.Checked = False

        SetupName.Text = ""
        SetupID.Text = 0

        TotalGamesLB.Text = "0"
        MatchedLB.Text = "0"
        UnmatchedLB.Text = "0"

    End Sub

    Private Sub RefreshHighlightVars(sender As Object, e As EventArgs) Handles ComparitorFoldersCB.SelectedIndexChanged, ComparitorCB.SelectedIndexChanged, ComparitorFieldCB.SelectedIndexChanged

        If DGV1.Rows.Count = 0 Then Return

        Debug.WriteLine("Filer change")

        Dim CField As String = ComparitorFieldCB.Text
        Dim folders As String = ComparitorFoldersCB.Text

        Dim col1 As String = ""
        Dim col2 As String = ""

        Select Case folders
            Case "Gray and Blue"
                col1 = "F1" & CField
                col2 = "F2" & CField
            Case "Blue and Green"
                col1 = "F2" & CField
                col2 = "F3" & CField
            Case "Gray and Green"
                col1 = "F1" & CField
                col2 = "F3" & CField
        End Select

        F1Col = DGV1.Columns.Item(col1).Index
        F2Col = DGV1.Columns.Item(col2).Index
        HLOprtr = ComparitorCB.Text

        Debug.WriteLine("Filterchange out: {0}, {1}, {2}", F1Col, F2Col, HLOprtr)

    End Sub

    Private Sub PopulateSetup(ID As Integer)
        Dim selrow() As DataRow
        selrow = _KeepDS.Tables("Setups").Select("ID = " & ID)

        SetupName.Text = selrow(0).Item("Name")
        SetupID.Text = selrow(0).Item("ID")

        NewTB.Text = selrow(0).Item("NewTitle")
        FPNew.Tag = selrow(0).Item("NewFolder")
        FPNew.Text = CompactString(selrow(0).Item("NewFolder"), FPNew.Width, FPNew.Font, TextFormatFlags.PathEllipsis)
        _NewItemsFolder = FPNew.Tag

        LocalTB.Text = selrow(0).Item("LocalTitle")
        FPLocal.Tag = selrow(0).Item("LocalFolder")
        FPLocal.Text = CompactString(selrow(0).Item("LocalFolder"), FPLocal.Width, FPLocal.Font, TextFormatFlags.PathEllipsis)
        _LocalItemsFolder = FPLocal.Tag

        CloudTB.Text = selrow(0).Item("CloudTitle")
        FPCloud.Tag = selrow(0).Item("CloudFolder")
        FPCloud.Text = CompactString(selrow(0).Item("CloudFolder"), FPCloud.Width, FPCloud.Font, TextFormatFlags.PathEllipsis)
        _CloudSyncFolder = FPCloud.Tag

        ResizeTB.Text = selrow(0).Item("ResizeTitle")
        FPResize.Tag = selrow(0).Item("ResizeFolder")
        FPResize.Text = CompactString(selrow(0).Item("ResizeFolder"), FPResize.Width, FPResize.Font, TextFormatFlags.PathEllipsis)
        _ResizeFolder = FPResize.Tag

        DatTB.Text = selrow(0).Item("DATTitle")
        FPDat.Tag = selrow(0).Item("DATFile")
        FPDat.Text = CompactString(selrow(0).Item("DATFile"), FPDat.Width, FPDat.Font, TextFormatFlags.PathEllipsis)
        _ListFilepath = FPDat.Tag

        SetupCB.Text = selrow(0).Item("Name")
        SystemsCB.Text = selrow(0).Item("System")
        DefaultChB.Checked = selrow(0).Item("Startup")

        GameColumnTB.Text = selrow(0).Item("FilenameCol").ToString

        log.Log_Data("Setup populated in form")

    End Sub


    Private Sub ComboBox1_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles ComparitorCB.DrawItem

        If e.Index <> -1 Then
            e.Graphics.DrawImage(Me.ImageList1.Images(e.Index) _
             , e.Bounds.Left, e.Bounds.Top)
        End If

    End Sub


    Private Sub ComboBox1_MeasureItem(ByVal sender As Object, ByVal e As System.Windows.Forms.MeasureItemEventArgs) Handles ComparitorCB.MeasureItem

        e.ItemHeight = Me.ImageList1.ImageSize.Height
        e.ItemWidth = Me.ImageList1.ImageSize.Width

    End Sub


    Function CompactString(ByVal MyString As String, ByVal Width As Integer,
    ByVal Font As Drawing.Font,
    ByVal FormatFlags As Windows.Forms.TextFormatFlags) As String
        'Ellipsis function on filepaths...
        Dim Result As String = String.Copy(MyString)

        TextRenderer.MeasureText(Result, Font, New Drawing.Size(Width, 0),
            FormatFlags Or TextFormatFlags.ModifyString)

        Return Result

    End Function


    Sub setupDGV()

        With DGV1
            '.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
            .ShowCellToolTips = False
            .VirtualMode = True
            .GetType.InvokeMember("DoubleBuffered", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.SetProperty, Nothing, DGV1, New Object() {True})

            With .Columns("Sel")
                .DisplayIndex = 0
                .SortMode = DataGridViewColumnSortMode.Automatic
                .HeaderText = "Select"
            End With

            With .Columns("NoMatch")
                .DisplayIndex = 1
                .ReadOnly = True
                .Visible = True
                .HeaderText = "Orphan"
                .SortMode = DataGridViewColumnSortMode.Automatic
            End With

            With .Columns("GGameName")
                '.AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader
                .HeaderCell.Value = "Database GameName"
                .DisplayIndex = 2
            End With



            With .Columns("GPrimaryFilename")
                '.AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader
                .HeaderCell.Value = "Database FileName"
                .DisplayIndex = 3
                .Frozen = True
            End With

            With .Columns("SafeGameName")
                '.AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader
                .HeaderCell.Value = "Filesafe GameName"
                .DisplayIndex = 4
            End With

            With .Columns("GID")
                .Visible = False
            End With




            '1 - New
            With .Columns("F1FileName")
                .DefaultCellStyle.BackColor = Color.Gainsboro
                .HeaderCell.Value = "File1"
            End With
            With .Columns("F1Width")
                .DefaultCellStyle.BackColor = Color.Gainsboro
                .HeaderCell.Value = "Width"
            End With
            With .Columns("F1Height")
                .DefaultCellStyle.BackColor = Color.Gainsboro
                .HeaderCell.Value = "Height"
            End With
            With .Columns("F1Size")
                .DefaultCellStyle.BackColor = Color.Gainsboro
                .HeaderCell.Value = "Size"
            End With
            With .Columns("F1Ext")
                .DefaultCellStyle.BackColor = Color.Gainsboro
                .HeaderCell.Value = "Ext"
            End With
            With .Columns("F1BitDepth")
                .DefaultCellStyle.BackColor = Color.Gainsboro
                .Visible = False
                .HeaderCell.Value = "Bit Depth"
            End With
            With .Columns("F1VPPi")
                .DefaultCellStyle.BackColor = Color.Gainsboro
                .Visible = False
                .HeaderCell.Value = "Vert PPI"
            End With
            With .Columns("F1HPPi")
                .DefaultCellStyle.BackColor = Color.Gainsboro
                .Visible = False
                .HeaderCell.Value = "Horiz PPI"
            End With
            With .Columns("F1Readonly?")
                .DefaultCellStyle.BackColor = Color.Gainsboro
                .Visible = False
                .HeaderCell.Value = "Read Only?"
            End With
            With .Columns("F1DateLastSaved")
                .DefaultCellStyle.BackColor = Color.Gainsboro
                .Visible = False
                .HeaderCell.Value = "Date Last Saved"
            End With
            With .Columns("F1DateCreated")
                .DefaultCellStyle.BackColor = Color.Gainsboro
                .Visible = False
                .HeaderCell.Value = "Date Created"
            End With
            With .Columns("F1DateAccessed")
                .DefaultCellStyle.BackColor = Color.Gainsboro
                .Visible = False
                .HeaderCell.Value = "Date Accessed"
            End With

            With .Columns("F1Flag")
                '.SortMode = DataGridViewColumnSortMode.Automatic
            End With


            '2 - Local
            With .Columns("F2FileName")
                .DefaultCellStyle.BackColor = Color.LightSkyBlue
                .HeaderCell.Value = "File2"
            End With
            With .Columns("F2Width")
                .DefaultCellStyle.BackColor = Color.LightSkyBlue
                .HeaderCell.Value = "Width"
            End With
            With .Columns("F2Height")
                .DefaultCellStyle.BackColor = Color.LightSkyBlue
                .HeaderCell.Value = "Height"
            End With
            With .Columns("F2Size")
                .DefaultCellStyle.BackColor = Color.LightSkyBlue
                .HeaderCell.Value = "Size"
            End With
            With .Columns("F2Ext")
                .DefaultCellStyle.BackColor = Color.LightSkyBlue
                .HeaderCell.Value = "Ext"
            End With
            With .Columns("F2BitDepth")
                .DefaultCellStyle.BackColor = Color.LightSkyBlue
                .Visible = False
                .HeaderCell.Value = "Bit Depth"
            End With
            With .Columns("F2VPPi")
                .DefaultCellStyle.BackColor = Color.LightSkyBlue
                .Visible = False
                .HeaderCell.Value = "Vert PPI"
            End With
            With .Columns("F2HPPi")
                .DefaultCellStyle.BackColor = Color.LightSkyBlue
                .Visible = False
                .HeaderCell.Value = "Horiz PPI"
            End With
            With .Columns("F2Readonly?")
                .DefaultCellStyle.BackColor = Color.LightSkyBlue
                .Visible = False
                .HeaderCell.Value = "Read Only?"
            End With
            With .Columns("F2DateLastSaved")
                .DefaultCellStyle.BackColor = Color.LightSkyBlue
                .Visible = False
                .HeaderCell.Value = "Date Last Saved"
            End With
            With .Columns("F2DateCreated")
                .DefaultCellStyle.BackColor = Color.LightSkyBlue
                .Visible = False
                .HeaderCell.Value = "Date Created"
            End With
            With .Columns("F2DateAccessed")
                .DefaultCellStyle.BackColor = Color.LightSkyBlue
                .Visible = False
                .HeaderCell.Value = "Date Accessed"
            End With

            With .Columns("F2Flag")
                '.SortMode = DataGridViewColumnSortMode.Automatic
            End With

            '.Columns.Add(New DataGridViewImageColumn With {.Name = "F2F3", .ImageLayout = DataGridViewImageCellLayout.Zoom, .Width = 32})
            '.Columns("F2F3").DisplayIndex = DGV1.Columns("F2DateAccessed").Index + 1


            '3 - Cloud
            With .Columns("F3FileName")
                .DefaultCellStyle.BackColor = Color.DarkSeaGreen
                .HeaderCell.Value = "File3"
            End With
            With .Columns("F3Width")
                .DefaultCellStyle.BackColor = Color.DarkSeaGreen
                .HeaderCell.Value = "Width"
            End With
            With .Columns("F3Height")
                .DefaultCellStyle.BackColor = Color.DarkSeaGreen
                .HeaderCell.Value = "Height"
            End With
            With .Columns("F3Size")
                .DefaultCellStyle.BackColor = Color.DarkSeaGreen
                .HeaderCell.Value = "Size"
            End With
            With .Columns("F3Ext")
                .DefaultCellStyle.BackColor = Color.DarkSeaGreen
                .HeaderCell.Value = "Ext"
            End With
            With .Columns("F3BitDepth")
                .DefaultCellStyle.BackColor = Color.DarkSeaGreen
                .Visible = False
                .HeaderCell.Value = "Bit Depth"
            End With
            With .Columns("F3VPPi")
                .DefaultCellStyle.BackColor = Color.DarkSeaGreen
                .Visible = False
                .HeaderCell.Value = "Vert PPI"
            End With
            With .Columns("F3HPPi")
                .DefaultCellStyle.BackColor = Color.DarkSeaGreen
                .Visible = False
                .HeaderCell.Value = "Horiz PPI"
            End With
            With .Columns("F3Readonly?")
                .DefaultCellStyle.BackColor = Color.DarkSeaGreen
                .Visible = False
                .HeaderCell.Value = "Read Only?"
            End With
            With .Columns("F3DateLastSaved")
                .DefaultCellStyle.BackColor = Color.DarkSeaGreen
                .Visible = False
                .HeaderCell.Value = "Date Last Saved"
            End With
            With .Columns("F3DateCreated")
                .DefaultCellStyle.BackColor = Color.DarkSeaGreen
                .Visible = False
                .HeaderCell.Value = "Date Created"
            End With
            With .Columns("F3DateAccessed")
                .DefaultCellStyle.BackColor = Color.DarkSeaGreen
                .Visible = False
                .HeaderCell.Value = "Date Accessed"
            End With



        End With
    End Sub


    Private Sub DGV1_CellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles DGV1.CellEnter
        'DGV1 Cell Enter
        If DGV1.Columns(e.ColumnIndex).HeaderText = "Database FileName" Then
            Dim gameno As Integer = DGV1.Rows(e.RowIndex).Cells("GID").Value
            'Dim clones() As String = _GSMDS.Tables("AltFilenames").Select("GID = " & gameno)
            Dim TTout As String = ""

            Dim clones = _
            From G In _GSMDS.Tables("AltFilenames") _
            Where G.Field(Of Integer)("GamesID") = gameno _
            Select New With {
                .name = G.Field(Of String)("Filename"),
                .standard = G.Field(Of String)("Standard")
                }

            For Each clone In clones
                Debug.WriteLine(clone.name)
                TTout = TTout & clone.standard & ": " & clone.name & vbCr
            Next

            Dim cell = DGV1.CurrentCell
            Dim cellDisplayRect = DGV1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, False)
            InstantTT.Show(String.Format(TTout, e.ColumnIndex, e.RowIndex), DGV1, cellDisplayRect.X + cell.Size.Width / 1.5, cellDisplayRect.Y + cell.Size.Height / 1.5, 20000)
            DGV1.ShowCellToolTips = False
        Else
            InstantTT.Hide(Me)
        End If

    End Sub



    Public Function RemoveBracketedText(Str As String) As String

        Str = Regex.Replace(Str, "\[(.*?)\]", "")
        Str = Regex.Replace(Str, "\((.*?)\)", "")
        Return Str

    End Function

    Private Sub setup()

        'TESTS
        'Var instance

        'End Tests

        ProgressPanel.Visible = True
        TabControl1.Enabled = False
        Me.Cursor = Cursors.WaitCursor

        If InitialiseFiles() = False Then
            TabControl1.Enabled = True
            Me.Cursor = Cursors.Default
            log.Log_Error("Initialising files - setup load aborted")
            Return
        End If


        'tests
        'Setup Folders in DB

        With _FileParser
            .FolderToParse = _NewItemsFolder
            .Extentions = _ImgExts
            .FolderParse("New")
            .FullDetails = ShowFullInfoChB.Checked
        End With

        With _FileParser
            .FolderToParse = _LocalItemsFolder
            .Extentions = _ImgExts
            .FolderParse("Local")
            .FullDetails = ShowFullInfoChB.Checked
        End With

        With _FileParser
            .FolderToParse = _CloudSyncFolder
            .Extentions = _ImgExts
            .FolderParse("Cloud")
            .FullDetails = ShowFullInfoChB.Checked
        End With
        log.Log_Data("All folders parsed succesfully")
        'SetupDV
        ConstructBehemoth(1, "PrimaryFilename")
        log.Log_Data("Datagrid contrusted succesfully")

        PB1.Value = 0
        OperationLB.Text = ""

        ProgressPanel.Visible = False
        TabControl1.Enabled = True
        Me.Cursor = Cursors.Default
        Me.TabControl1.SelectedIndex = 1

        GamesLoaded = True
        TabControl1.TabPages(1).Enabled = True
        TabControl1.TabPages(2).Enabled = True

        '  Initialise_DGV()

    End Sub

    Private Function InitialiseFiles() As Boolean
        'sets up datables for folders
        AddFolders()


        'Import XML file
        'XML
        _Listxml.Filepath = _ListFilepath
        _Listxml.Dataset = _ListDataset
        log.Log_Data("Attempting to load system dat: " & _ListFilepath)
        log.Log_Data("System and field: " & SystemsCB.Text & " ," & GameColumnTB.Text)
        Dim SystemSel As String = SystemsCB.Text
        Select Case SystemSel

            Case "MAME"
                If _Listxml.ImportXML() = False Then
                    log.Log_Error("importing MAME .xml")
                    Return False
                End If
                AddMameSystem()
                _Listxml.TransferMame(_ListDataset, _GSMDS.Tables("Games"), _GSMDS.Tables("AltFilenames"))
                log.Log_Data("XML transferred successfully into GSM working database.")

            Case "GameEx"

                AddGESystem()
                'Dim readdb3 As New XMLOps
                If _Listxml.ImportGEDb3(_ListFilepath,
                                    _GSMDS.Tables("Games"),
                                    _GSMDS.Tables("AltFilenames"),
                                    GameColumnTB.Text) = False Then
                    log.Log_Error("importing GameEx db3.")
                    Return False
                End If
                log.Log_Error("Successfully imported GameEx db3.")
                Return True

            Case "HyperList"
                If _Listxml.ImportXML() = False Then
                    log.Log_Error("importing HyperList .xml")
                    Return False
                End If
                AddHSSystem()
                If _Listxml.TransferHyperSpin(_ListDataset, _GSMDS.Tables("Games"), _GSMDS.Tables("AltFilenames")) = False Then
                    log.Log_Error("Error Importing Hyperlist XML.")
                Else
                    log.Log_Data("Hyperlist XML transferred successfully into GSM working database.")
                End If

        End Select
        Return True

    End Function

    Private Sub SetupMainDT()
        _MainDT.Columns.Add("Sel", GetType(Boolean))
        _MainDT.Columns("Sel").DefaultValue = False
        _MainDT.Columns.Add("GID", GetType(Int32))
        _MainDT.Columns.Add("GGameName")
        _MainDT.Columns.Add("SafeGameName")
        _MainDT.Columns.Add("GPrimaryFilename") ' - Used as IMage filename
        ' _MainDT.Columns.Add("GamePrimaryFilename") ' - Filename from Games DB


        _MainDT.Columns.Add("F1FileName")
        _MainDT.Columns.Add("F1Width", GetType(Int32))

        _MainDT.Columns.Add("F1Height", GetType(Int32))

        _MainDT.Columns.Add("F1Size", GetType(Double))


        _MainDT.Columns.Add("F1Ext")
        _MainDT.Columns.Add("F1BitDepth")
        _MainDT.Columns.Add("F1VPPi")
        _MainDT.Columns.Add("F1HPPi")
        _MainDT.Columns.Add("F1Readonly?")
        _MainDT.Columns.Add("F1DateLastSaved")
        _MainDT.Columns.Add("F1DateCreated")
        _MainDT.Columns.Add("F1DateAccessed")
        '_MainDT.Columns.Add("F1Flag", GetType(Boolean))
        '_MainDT.Columns.Add("F1F2Rel", GetType(String))

        _MainDT.Columns.Add("F2FileName")
        _MainDT.Columns.Add("F2Width", GetType(Int32))
        _MainDT.Columns.Add("F2Height", GetType(Int32))
        _MainDT.Columns.Add("F2Size", GetType(Double))
        _MainDT.Columns.Add("F2Ext")
        _MainDT.Columns.Add("F2BitDepth")
        _MainDT.Columns.Add("F2VPPi")
        _MainDT.Columns.Add("F2HPPi")
        _MainDT.Columns.Add("F2Readonly?")
        _MainDT.Columns.Add("F2DateLastSaved")
        _MainDT.Columns.Add("F2DateCreated")
        _MainDT.Columns.Add("F2DateAccessed")
        '_MainDT.Columns.Add("F2Flag", GetType(Boolean))
        '_MainDT.Columns.Add("F2F3Rel", GetType(String))

        _MainDT.Columns.Add("F3FileName")
        _MainDT.Columns.Add("F3Width", GetType(Int32))
        _MainDT.Columns.Add("F3Height", GetType(Int32))
        _MainDT.Columns.Add("F3Size", GetType(Double))
        _MainDT.Columns.Add("F3Ext")
        _MainDT.Columns.Add("F3BitDepth")
        _MainDT.Columns.Add("F3VPPi")
        _MainDT.Columns.Add("F3HPPi")
        _MainDT.Columns.Add("F3Readonly?")
        _MainDT.Columns.Add("F3DateLastSaved")
        _MainDT.Columns.Add("F3DateCreated")
        _MainDT.Columns.Add("F3DateAccessed")

        _MainDT.Columns.Add("NoMatch", GetType(Boolean))
        _MainDT.Columns("NoMatch").DefaultValue = False

        'Defaults
        _MainDT.Columns("F1Width").DefaultValue = 0
        _MainDT.Columns("F1Height").DefaultValue = 0
        _MainDT.Columns("F1Size").DefaultValue = 0
        _MainDT.Columns("F2Width").DefaultValue = 0
        _MainDT.Columns("F2Height").DefaultValue = 0
        _MainDT.Columns("F2Size").DefaultValue = 0
        _MainDT.Columns("F3Width").DefaultValue = 0
        _MainDT.Columns("F3Height").DefaultValue = 0
        _MainDT.Columns("F3Size").DefaultValue = 0

    End Sub

    Private Sub ConstructBehemoth(System As Integer, GameFile As String)

        Debug.WriteLine(vbCr & "BEHEMOTH!!!!!!!")

        Dim Games As DataTable = _GSMDS.Tables("Games")
        Dim Files As DataTable = _GSMDS.Tables("Files")

        If _MainDT.Columns.Count = 0 Then
            SetupMainDT()
        Else
            DGV1.DataSource = Nothing
            _MainDT.Clear()
        End If

        Dim query1 = _
            From G In Games _
            Where G.Field(Of Integer)("SystemID") = System _
            Join F In Files On _
            G.Field(Of String)("PrimaryFilename") Equals F.Field(Of String)("Name") _
            Select New With {
                .gid = G.Field(Of Integer)("ID"),
                .ggamename = G.Field(Of String)("GameName"),
                .gprimaryfilename = G.Field(Of String)("PrimaryFilename"),
                .gsafegamename = G.Field(Of String)("SafeGameName"),
                .fID = F.Field(Of Integer)("FolderID"),
                .fFilename = F.Field(Of String)("FileName"),
                .fheight = F.Field(Of Int32)("Height"),
                .fwidth = F.Field(Of Int32)("Width"),
                 .fBitDepth = F.Field(Of String)("BitDepth"),
                .fext = F.Field(Of String)("FileExtention"),
                .fsize = F.Field(Of Double)("FileSize"),
               .fvppi = F.Field(Of String)("VPpi"),
                .fhppi = F.Field(Of String)("HPpi"),
                .freadonly = F.Field(Of Boolean)("ReadOnly?"),
                .fdatesaved = F.Field(Of String)("DateLastSaved"),
                .fdatecreated = F.Field(Of String)("DateCreated"),
                .fdateaccessed = F.Field(Of String)("DateAccessed")}

        Dim query2 As New Object
        If My.Settings.IncImgsMatchGN Then
            query2 = _
                   From G In Games _
                   Where G.Field(Of Integer)("SystemID") = System _
                   Join F In Files On _
                   G.Field(Of String)("SafeGameName") Equals F.Field(Of String)("Name") _
                   Select New With {
                       .gid = G.Field(Of Integer)("ID"),
                       .ggamename = G.Field(Of String)("GameName"),
                       .gprimaryfilename = G.Field(Of String)("PrimaryFilename"),
                        .gsafegamename = G.Field(Of String)("SafeGameName"),
                       .fID = F.Field(Of Integer)("FolderID"),
                       .fFilename = F.Field(Of String)("FileName"),
                       .fheight = F.Field(Of Int32)("Height"),
                       .fwidth = F.Field(Of Int32)("Width"),
                        .fBitDepth = F.Field(Of String)("BitDepth"),
                       .fext = F.Field(Of String)("FileExtention"),
                       .fsize = F.Field(Of Double)("FileSize"),
                      .fvppi = F.Field(Of String)("VPpi"),
                       .fhppi = F.Field(Of String)("HPpi"),
                       .freadonly = F.Field(Of Boolean)("ReadOnly?"),
                       .fdatesaved = F.Field(Of String)("DateLastSaved"),
                       .fdatecreated = F.Field(Of String)("DateCreated"),
                       .fdateaccessed = F.Field(Of String)("DateAccessed")}
        Else
            query2 = _
                  From G In Games _
                  Where G.Field(Of Integer)("SystemID") = -999
                  Join F In Files On _
                   G.Field(Of String)("SafeGameName") Equals F.Field(Of String)("Name") _
                   Select New With {
                       .gid = G.Field(Of Integer)("ID"),
                       .ggamename = G.Field(Of String)("GameName"),
                       .gprimaryfilename = G.Field(Of String)("PrimaryFilename"),
                        .gsafegamename = G.Field(Of String)("SafeGameName"),
                       .fID = F.Field(Of Integer)("FolderID"),
                       .fFilename = F.Field(Of String)("FileName"),
                       .fheight = F.Field(Of Int32)("Height"),
                       .fwidth = F.Field(Of Int32)("Width"),
                        .fBitDepth = F.Field(Of String)("BitDepth"),
                       .fext = F.Field(Of String)("FileExtention"),
                       .fsize = F.Field(Of Double)("FileSize"),
                      .fvppi = F.Field(Of String)("VPpi"),
                       .fhppi = F.Field(Of String)("HPpi"),
                       .freadonly = F.Field(Of Boolean)("ReadOnly?"),
                       .fdatesaved = F.Field(Of String)("DateLastSaved"),
                       .fdatecreated = F.Field(Of String)("DateCreated"),
                       .fdateaccessed = F.Field(Of String)("DateAccessed")}
        End If

        Dim query = query1.Union(query2)

        Debug.WriteLine("FINAL QUERY -----------------------")
        'For Each item In query
        '    Debug.WriteLine(item.gid & ". " & item.ggamename)
        'Next
        ' MsgBox("here")

        OperationLB.Text = "Adding any game-image matches to the datagrid (" & query.Count & " records)"
        PB1.Minimum = 0
        PB1.Maximum = query.Count
        Dim count As Integer = 0
        Application.DoEvents()

        Dim newrow As DataRow = Nothing
        '  Dim addrowasnew As Boolean = False
        Dim AddedGIDs As New Dictionary(Of Integer, List(Of Integer))
        'AddedGIDs.Clear()
        Dim MatchedCount As Integer = 0
        Dim UpdateRow = False

        'THIS IS A FUTHERMUCKER - messes up 1st and last in some queries - totally confuised - means two games don't work properly in DGV

        _MainDT.BeginLoadData()

        For Each q In query
            'Dim foundrow() As DataRow = _MainDT.Select("GID='" & q.gid & "'")
            Debug.WriteLine("----------------------------------")
            Debug.WriteLine("Query row: " & q.gid & ". " & q.ggamename & " | " & q.gprimaryfilename)
            Dim folders As New List(Of Integer)

            If q.ggamename = "007: Racing" Then
                Debug.WriteLine("----------------------------------")
                'break here
            End If

            If AddedGIDs.TryGetValue(q.gid, folders) Then

                Debug.WriteLine("Game " & q.gid & " already exists - check if folder already written")
                If newrow("GID") <> q.gid Then
                    'Same game but second query
                    'write 'old' datarow:
                    If UpdateRow Then
                    Else
                        _MainDT.Rows.Add(newrow)
                    End If

                    'write second query to new datarow:
                    newrow = _MainDT.Select("GID = " & q.gid)(0)
                    UpdateRow = True
                End If

                If folders.Contains(q.fID) Then
                    Debug.WriteLine("Folder already written - skip iteration")
                    count = count + 1
                    Continue For
                Else
                    'GID exists but this folder not processed - add to checker
                    Debug.WriteLine("GID exists but this folder not processed - add to checker")
                    Dim newval As List(Of Integer) = AddedGIDs(q.gid)
                    newval.Add(q.fID)
                    AddedGIDs(q.gid) = newval
                End If
            Else
                'New Game ID - write datarow of last Game
                If newrow Is Nothing Then
                    'nothing
                    'Controls for first iteration
                Else
                    'Debug.WriteLine("New Game ID - write datarow of last Game, if not an update row")
                    If UpdateRow = False Then _MainDT.Rows.Add(newrow)
                End If
                newrow = _MainDT.NewRow
                UpdateRow = False
                Dim newval As New List(Of Integer)
                newval.Add(q.fID)
                AddedGIDs.Add(q.gid, newval)
                MatchedCount += 1
            End If

            newrow("GID") = q.gid
            newrow("GGameName") = q.ggamename
            newrow("SafeGameName") = q.gsafegamename
            newrow("GPrimaryFilename") = NotNull(q.gprimaryfilename, SafeFilename(q.ggamename))
            newrow("F" & q.fID & "FileName") = q.fFilename
            newrow("F" & q.fID & "Width") = q.fwidth
            newrow("F" & q.fID & "Height") = q.fheight
            newrow("F" & q.fID & "Size") = q.fsize
            newrow("F" & q.fID & "Ext") = q.fext
            newrow("F" & q.fID & "BitDepth") = q.fBitDepth
            newrow("F" & q.fID & "VPPi") = q.fvppi
            newrow("F" & q.fID & "HPPi") = q.fhppi
            newrow("F" & q.fID & "Readonly?") = q.freadonly
            newrow("F" & q.fID & "DateLastSaved") = q.fdatesaved
            newrow("F" & q.fID & "DateCreated") = q.fdatecreated
            newrow("F" & q.fID & "DateAccessed") = q.fdateaccessed


            count = count + 1
            PB1.Value = count
            Application.DoEvents()

        Next

        _MainDT.EndLoadData()

        If UpdateRow = False Then _MainDT.Rows.Add(newrow)
        Debug.WriteLine("Last query written")

        'ADD NON MATCHED IF SETTINGS PERMIT
        If My.Settings.InclUnmatched = True Then
            Dim t1 As DataTable = _GSMDS.Tables("Games")
            Dim t2 As DataTable = _MainDT
            Dim Diff = From c In t1 _
                       Group Join d In t2 _
                       On c.Field(Of Integer)("ID") Equals d.Field(Of Integer)("GID") _
                       Into cds = Group From f In cds.DefaultIfEmpty() _
                        Where f Is Nothing
                         Select New With { _
                        .gname = c.Field(Of String)("GameName"), _
                    .gfile = c.Field(Of String)("PrimaryFilename"), _
                    .gID = c.Field(Of Int32)("ID")}

            OperationLB.Text = "Include unmatched checked in settings. Adding any unmatched (" & Diff.Count & " records)..."
            PB1.Minimum = 0
            PB1.Maximum = Diff.Count
            count = 0
            Application.DoEvents()

            For Each missinggame In Diff
                Debug.WriteLine("Adding non-matched: " & missinggame.gname)
                newrow = _MainDT.NewRow
                newrow("GID") = missinggame.gID
                newrow("GGameName") = missinggame.gname
                newrow("GPrimaryFilename") = missinggame.gfile
                newrow("NoMatch") = True
                _MainDT.Rows.Add(newrow)

                count = count + 1
                PB1.Value = count
                Application.DoEvents()
            Next
        End If



        'gamename = G.Field(Of Integer)("GameName"), _
        'primary = G.Field(Of Integer)("PrimaryFilename"), _
        'width = F.Field(Of Integer)("Width")


        ' =========== DGV Ops ================
        OperationLB.Text = "Preparing datagrid for viewing...."
        Application.DoEvents()
        DGV1.DataSource = _MainDT
        Application.DoEvents()

        'Any post binds ops:
        setupDGV()


        count = 0
        PB1.Maximum = DGV1.Columns.Count
        PB1.Value = 1
        For Each column As DataGridViewColumn In DGV1.Columns
            If column.HeaderText = "Sel" Then
                'leave
            Else
                column.ReadOnly = True
            End If
            count = count + 1
            PB1.Value = count
            Application.DoEvents()
        Next


        With DGV1
            .AllowUserToResizeColumns = True
            .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
            With .Columns("GPrimaryFilename")
                .Visible = False

                .AutoSizeMode = DataGridViewAutoSizeColumnMode.None
            End With
            'With .Columns("SafeGameName")
            '    .Visible = False
            'End With
            With .Columns("GGameName")

                .AutoSizeMode = DataGridViewAutoSizeColumnMode.None
                .Width = 250
            End With
            With .Columns("SafeGameName")
                .AutoSizeMode = DataGridViewAutoSizeColumnMode.None
                .Visible = False
            End With
            With .Columns("F1FileName")
                .Visible = False
                .AutoSizeMode = DataGridViewAutoSizeColumnMode.None
            End With
            With .Columns("F2FileName")
                .Visible = False
                .AutoSizeMode = DataGridViewAutoSizeColumnMode.None
            End With
            With .Columns("F3FileName")
                .Visible = False
                .AutoSizeMode = DataGridViewAutoSizeColumnMode.None
            End With

            '.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None
            .AllowUserToResizeColumns = True
            .Columns("Sel").ReadOnly = False
        End With

        'Populate Totals
        TotalGamesLB.Text = _GSMDS.Tables("Games").Rows.Count.ToString
        MatchedLB.Text = MatchedCount
        UnmatchedLB.Text = CInt(_GSMDS.Tables("Games").Rows.Count) - MatchedCount

    End Sub


    Private Sub AddMameSystem()
        Dim newrow As DataRow
        newrow = _GSMDS.Tables("Systems").NewRow
        newrow("SystemName") = "MAME"
        _GSMDS.Tables("Systems").Rows.Add(newrow)
    End Sub

    Private Sub AddGESystem()
        Dim newrow As DataRow
        newrow = _GSMDS.Tables("Systems").NewRow
        newrow("SystemName") = "GameEx"
        _GSMDS.Tables("Systems").Rows.Add(newrow)
    End Sub

    Private Sub AddHSSystem()
        Dim newrow As DataRow
        newrow = _GSMDS.Tables("Systems").NewRow
        newrow("SystemName") = "HyperSpin"
        _GSMDS.Tables("Systems").Rows.Add(newrow)
    End Sub

    Private Sub AddFolders()
        Dim newrow As DataRow

        newrow = _GSMDS.Tables("Folders").NewRow
        'New Folder:
        newrow("FolderName") = "New"
        newrow("Description") = "Any new files being considered..."
        newrow("FolderPath") = _NewItemsFolder
        newrow("Synced?") = False
        newrow("Cloud?") = False
        _GSMDS.Tables("Folders").Rows.Add(newrow)

        newrow = _GSMDS.Tables("Folders").NewRow
        'Local Folder:
        newrow("FolderName") = "Local"
        newrow("Description") = "Your Local Image set..."
        newrow("FolderPath") = _LocalItemsFolder
        newrow("Synced?") = False
        newrow("Cloud?") = False
        _GSMDS.Tables("Folders").Rows.Add(newrow)

        newrow = _GSMDS.Tables("Folders").NewRow
        'Cloud Folder:
        newrow("FolderName") = "Cloud"
        newrow("Description") = "Your Cloud folder..."
        newrow("FolderPath") = _CloudSyncFolder
        newrow("Synced?") = True
        newrow("Cloud?") = True
        _GSMDS.Tables("Folders").Rows.Add(newrow)

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs)
        'Break
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles LoadDT.Click

        ' ================= CHECKS =============================
        If SetupCB.Text = "" Then Return
        ' Check there is existing record + other checks:
        Dim selrow() As DataRow
        selrow = _KeepDS.Tables("Setups").Select("Name = '" & SetupCB.Text & "'")
        If selrow.Count = 0 Then
            MsgBox("There is no saved Setup of that name. Please check...")
            Return
        End If
        If selrow(0).Item("NewFolder") = "" Or
            selrow(0).Item("LocalFolder") = "" Or
                selrow(0).Item("CloudFolder") = "" Then
            MsgBox("There must be a path specified for all of the folders. You can use a dummy path if required.")
            Return
        End If

        log.Log_Data("Proceeding with setting up: " & SetupCB.Text, "load setup selected")

        'Check files and folders:
        If Not (My.Computer.FileSystem.DirectoryExists(_NewItemsFolder)) Then
            MsgBox("Grey folder doesn't exist.")
            Return
        ElseIf Not (My.Computer.FileSystem.DirectoryExists(_LocalItemsFolder)) Then
            MsgBox("Blue folder doesn't exist.")
            Return
        ElseIf Not (My.Computer.FileSystem.DirectoryExists(_CloudSyncFolder)) Then
            MsgBox("Green folder doesn't exist.")
            Return
        ElseIf Not (File.Exists(_ListFilepath)) Then
            MsgBox("File specified for the game data does not exist.")
            Return
        End If

        'IMPORT PROCESS ==========================
        'Clear the decks...
        _ListDataset.Clear()
        _MainDT.Clear()
        '_GSMDS.Tables("Games").Clear()
        '_GSMDS.Tables("AltFilenames").Clear()
        '_GSMDS.Tables("Files").Clear()

        _GSMDS.Clear()

        '   DGV1.DataSource = Nothing
        ' DGV1.Visible = False

        For Each dtable As DataTable In _GSMDS.Tables
            dtable.Columns("ID").AutoIncrementStep = -1
            dtable.Columns("ID").AutoIncrementSeed = -1
            dtable.Columns("ID").AutoIncrementStep = 1
            dtable.Columns("ID").AutoIncrementSeed = 1
        Next

        setup()

        'If HideGamenameChB.Checked = True Then
        '    If DGV1.Columns.Contains("GGameName") Then DGV1.Columns("GGameName").Visible = False
        'Else
        '    If DGV1.Columns.Contains("GGameName") Then DGV1.Columns("GGameName").Visible = True
        'End If

        log.Log_Data("Setup successfully loaded with " & TotalGamesLB.Text & " records.", "setup loaded")



    End Sub

    Private Sub OpenDatBT_Click(sender As Object, e As EventArgs) Handles OpenDatBT.Click
        With OFD1
            .Title = "Choose an XML, DAT or equivalent file to use."
            .Filter = "XML|*.xml|DAT|*.dat|DB3|*.db3|All Files|*.*"
            Try
                .InitialDirectory = _ListFilepath
                .FileName = Path.GetFileName(_ListFilepath)
            Catch
                .InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
                .FileName = "Default"
            End Try
        End With

        If OFD1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Try
                FPDat.Text = CompactString(OFD1.FileName, FPDat.Width, FPDat.Font, TextFormatFlags.PathEllipsis)
                FPDat.Tag = OFD1.FileName
                _ListFilepath = OFD1.FileName
            Catch

            End Try
        End If
    End Sub

    Private Sub OpenNewBT_Click(sender As Object, e As EventArgs) Handles OpenNewBT.Click
        With FBD

            If FPNew.Tag = "" Then
                'MsgBox("nothing!")
            Else
                .SelectedPath = FPNew.Tag
            End If
            .Description = "Choose the folder containing new images...."
        End With
        Dim result As DialogResult = FBD.ShowDialog()
        If result = Windows.Forms.DialogResult.OK Then
            FPNew.Text = CompactString(FBD.SelectedPath, FPNew.Width, FPNew.Font, TextFormatFlags.PathEllipsis)
            FPNew.Tag = FBD.SelectedPath
            _NewItemsFolder = FBD.SelectedPath
        End If
    End Sub

    Private Sub OpenLocalBT_Click(sender As Object, e As EventArgs) Handles OpenLocalBT.Click
        With FBD
            If FPLocal.Tag = "" Then
                'MsgBox("nothing!")
            Else
                .SelectedPath = FPLocal.Tag
            End If
            .Description = "Choose the folder containing your local image set...."
        End With
        Dim result As DialogResult = FBD.ShowDialog()
        If result = Windows.Forms.DialogResult.OK Then
            FPLocal.Text = CompactString(FBD.SelectedPath, FPLocal.Width, FPLocal.Font, TextFormatFlags.PathEllipsis)
            FPLocal.Tag = FBD.SelectedPath
            _LocalItemsFolder = FBD.SelectedPath
        End If
    End Sub

    Private Sub OpenCloudBT_Click(sender As Object, e As EventArgs) Handles OpenCloudBT.Click
        With FBD
            If FPCloud.Tag = "" Then
                'MsgBox("nothing!")
            Else
                .SelectedPath = FPCloud.Tag
            End If
            .Description = "Choose the folder containing your local image set...."
        End With
        Dim result As DialogResult = FBD.ShowDialog()
        If result = Windows.Forms.DialogResult.OK Then
            FPCloud.Text = CompactString(FBD.SelectedPath, FPCloud.Width, FPCloud.Font, TextFormatFlags.PathEllipsis)
            FPCloud.Tag = FBD.SelectedPath
            _CloudSyncFolder = FBD.SelectedPath
        End If
    End Sub

    Private Sub OpenResizeBT_Click(sender As Object, e As EventArgs) Handles OpenResizeBT.Click
        With FBD
            If FPResize.Tag = "" Then
                'MsgBox("nothing!")
            Else
                .SelectedPath = FPResize.Tag
            End If
            .Description = "Choose the folder containing your resized image set...."
        End With
        Dim result As DialogResult = FBD.ShowDialog()
        If result = Windows.Forms.DialogResult.OK Then
            FPResize.Text = CompactString(FBD.SelectedPath, FPResize.Width, FPResize.Font, TextFormatFlags.PathEllipsis)
            FPResize.Tag = FBD.SelectedPath
            _ResizeFolder = FBD.SelectedPath
        End If
    End Sub

    Private Sub DGV1_RowEnter(sender As Object, e As DataGridViewCellEventArgs) Handles DGV1.RowEnter
        Debug.WriteLine("row enter: {0}, {1}", e.RowIndex, e.ColumnIndex)

        Dim row As DataGridViewRow
        row = DGV1.Rows(e.RowIndex)

        FuzzyTB.Text = SafeFilename(DGV1.Rows(e.RowIndex).Cells("GGameName").Value)
        FuzzyGameID.Text = DGV1.Rows(e.RowIndex).Cells("GID").Value
        FuzzyFolderCB.Enabled = True
        FuzzyAddBT.Enabled = False

        GameSearchCB.Text = ""

        _GSMDS.Tables("Matches").Clear()


        FuzzyImagePB.Image = My.Resources.press_search

        Dim ImgFile1 As String = _NewItemsFolder & "\" & row.Cells("F1FileName").Value
        Dim ImgFile2 As String = _LocalItemsFolder & "\" & row.Cells("F2FileName").Value
        Dim ImgFile3 As String = _CloudSyncFolder & "\" & row.Cells("F3FileName").Value

        Dim fs As System.IO.FileStream

        Dim PrevImage As Image


        If IO.File.Exists(ImgFile1) Then
            ' Dim fs As System.IO.FileStream
            fs = New System.IO.FileStream(ImgFile1,
                    IO.FileMode.Open, IO.FileAccess.Read)
            Try
                PrevImage = Image.FromStream(fs)
            Catch
                PrevImage = My.Resources.broken_file_link
            End Try
            fs.Close()
        Else
            PrevImage = My.Resources.no_image
        End If
        NewPB.Image = PrevImage

        If Not String.IsNullOrEmpty(row.Cells("F1Size").Value.ToString) Then

            NewPB.Tag = "[" & NewTB.Text & "] " & row.Cells("GGameName").Value & ": " & row.Cells("F1FileName").Value _
                & " (" & row.Cells("F1Width").Value _
                & " x " & row.Cells("F1Height").Value _
                & ") " & ConvertKBytes(row.Cells("F1Size").Value)

            CompareNewLB.Text = "(" & row.Cells("F1Width").Value _
                & " x " & row.Cells("F1Height").Value _
                & ") " & ConvertKBytes(row.Cells("F1Size").Value)
        Else
            CompareNewLB.Text = "No Image"
        End If

        If IO.File.Exists(ImgFile2) Then
            ' Dim fs As System.IO.FileStream
            fs = New System.IO.FileStream(ImgFile2,
                    IO.FileMode.Open, IO.FileAccess.Read)
            Try
                PrevImage = Image.FromStream(fs)
            Catch
                PrevImage = My.Resources.broken_file_link
            End Try
            fs.Close()
        Else
            PrevImage = My.Resources.no_image
        End If
        LocalPB.Image = PrevImage

        If Not String.IsNullOrEmpty(row.Cells("F2Size").Value.ToString) Then
            CompareLocalLB.Text = "(" & row.Cells("F2Width").Value _
                & " x " & row.Cells("F2Height").Value _
                & ") " & ConvertKBytes(row.Cells("F2Size").Value)

            'newrow("GGameName") = q.ggamename
            'newrow("GPrimaryFilename") = q.gprimaryfilename
            LocalPB.Tag = "[" & LocalTB.Text & "] " & row.Cells("GGameName").Value & ": " & row.Cells("F2FileName").Value _
                & " (" & row.Cells("F2Width").Value _
                & " x " & row.Cells("F2Height").Value _
                & ") " & ConvertKBytes(row.Cells("F2Size").Value)
        Else
            CompareLocalLB.Text = "No Image"
        End If

        If IO.File.Exists(ImgFile3) Then
            '  Dim fs As System.IO.FileStream
            fs = New System.IO.FileStream(ImgFile3,
                    IO.FileMode.Open, IO.FileAccess.Read)
            Try
                PrevImage = Image.FromStream(fs)
            Catch
                PrevImage = My.Resources.broken_file_link
            End Try
            fs.Close()
        Else
            PrevImage = My.Resources.no_image
        End If
        CloudPB.Image = PrevImage

        If Not String.IsNullOrEmpty(row.Cells("F3Size").Value.ToString) Then

            CloudPB.Tag = "[" & CloudTB.Text & "] " & row.Cells("GGameName").Value & ": " & row.Cells("F1FileName").Value _
                & " (" & row.Cells("F3Width").Value _
                & " x " & row.Cells("F3Height").Value _
                & ") " & ConvertKBytes(row.Cells("F3Size").Value)

            CompareCloudLB.Text = "(" & row.Cells("F3Width").Value _
                & " x " & row.Cells("F3Height").Value _
                & ") " & ConvertKBytes(row.Cells("F3Size").Value)
        Else
            CompareCloudLB.Text = "No Image"
        End If

        TopSelectedRow = row.Cells("GID").Value

        'clear save as toggle
        UseFilenameTG.Tag = False
        UseFilenameTG.BackColor = SystemColors.Control

    End Sub

    Function ConvertKBytes(KBytes As Integer) As String

        Dim setkbytes As String = "0 KB"

        If KBytes >= 1073741824 Then
            setkbytes = Format(KBytes / 1024 / 1024 / 1024, "0") & "T"
        ElseIf KBytes >= 1048576 Then
            setkbytes = Format(KBytes / 1024 / 1024, "0") & " GB"
        ElseIf KBytes >= 1024 Then
            setkbytes = Format(KBytes / 1024, "0") & " MB"
        ElseIf KBytes < 1024 Then
            setkbytes = Format(KBytes, "0") & " KB"
        End If

        Return setkbytes

    End Function

    'Private Sub DGV1_Sorted(sender As Object, e As EventArgs) Handles DGV1.Sorted

    '    For Each Row As DataGridViewRow In DGV1.Rows
    '        Dim PrevImage As Image
    '        Dim ImgFile As String = _NewItemsFolder & "\" & Row.Cells("GPrimaryFilename").Value & Row.Cells("F1Ext").Value
    '        Debug.WriteLine("ImageFile: " & ImgFile)
    '        If IO.File.Exists(ImgFile) Then
    '            Try
    '                PrevImage = Image.FromFile(ImgFile)
    '            Catch
    '                PrevImage = My.Resources.folder_icon
    '            End Try

    '        Else
    '            PrevImage = My.Resources.folder_icon
    '        End If
    '        Row.Cells("F1Img").Value = PrevImage
    '    Next
    '    DGV1.Columns("F1Img").Width = 200



    '    ' newrow("F1Img") = _NewItemsFolder & "\" & q.gprimaryfilename & q.fext
    'End Sub

    Private Sub Label2_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub NewTB_TextChanged(sender As Object, e As EventArgs) Handles NewTB.TextChanged
        CompareNewGB.Text = NewTB.Text
    End Sub

    Private Sub LocalTB_TextChanged(sender As Object, e As EventArgs) Handles LocalTB.TextChanged
        CompareLocalGB.Text = LocalTB.Text
    End Sub

    Private Sub CloudTB_TextChanged(sender As Object, e As EventArgs) Handles CloudTB.TextChanged
        CompareCloudGB.Text = CloudTB.Text
    End Sub

    Private Sub SettsFont_Click(sender As Object, e As EventArgs) Handles SettsFont.Click
        With FD1
            .Font = My.Settings.UIFont
        End With

        If FD1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Me.Font = FD1.Font
            My.Settings.UIFont = FD1.Font
        End If
        My.Settings.Save()
        GameSearchTB.Font = New Font(My.Settings.UIFont.FontFamily, My.Settings.UIFont.Size, FontStyle.Bold)



    End Sub

    Private Sub ImageSize_KeyPress(sender As Object, e As KeyPressEventArgs) Handles SettsPrevW.KeyPress, SettsPrevH.KeyPress, MiniInfoTB.KeyPress
        If Asc(e.KeyChar) <> 8 Then
            If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
                e.Handled = True
            End If
        End If
    End Sub

    Private Sub ImageSize_Validated(sender As Object, e As System.EventArgs) Handles SettsPrevW.Validated, SettsPrevH.Validated, MiniInfoTB.Validated
        My.Settings.PrevW = CInt(SettsPrevW.Text)
        My.Settings.PrevH = CInt(SettsPrevH.Text)
        My.Settings.MiniInfoT = CInt(MiniInfoTB.Text)
    End Sub


    'Private Sub SettsShowPrev_CheckedChanged(sender As Object, e As EventArgs)
    '    If SettsShowPrev.Checked = True Then
    '        My.Settings.ShowPrev = True
    '    Else
    '        My.Settings.ShowPrev = False
    '    End If
    'End Sub

    Private Sub NewPB_Click(sender As Object, e As EventArgs) Handles NewPB.Click, LocalPB.Click, CloudPB.Click, FuzzyImagePB.Click

        If Not sender.image Is Nothing Then
            Debug.WriteLine("ImagePreview: " & sender.image.ToString)
            Dim pcontrol As Control = sender.Parent
            Dim NewImgPrev As New Preview
            NewImgPrev.Text = pcontrol.Text
            NewImgPrev.TopText = sender.tag
            NewImgPrev.ImgLayout = My.Settings.PrevLayout
            NewImgPrev.PrevImg = sender.image
            NewImgPrev.PictureBox = sender
            NewImgPrev.Show()
        End If

    End Sub




    Private Sub SettsImgLayCB_SelectedIndexChanged(sender As Object, e As EventArgs) Handles SettsImgLayCB.SelectedIndexChanged
        My.Settings.PrevLayout = SettsImgLayCB.Text
    End Sub



    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComparitorFieldCB.SelectedIndexChanged
        Debug.WriteLine("Comparitor Field: " & ComparitorFieldCB.Text)
        Debug.WriteLine("Comparitor Function: " & ComparitorCB.Text)
    End Sub


    'Private Sub CompareBT_Click(sender As Object, e As EventArgs)
    '    Debug.WriteLine(vbCr & "======= Compare Proceedure =========")
    '    Debug.WriteLine("Comparitor Field: " & ComparitorFieldCB.Text)
    '    Debug.WriteLine("Comparitor Function: " & ComparitorCB.Text)
    '    CompareMaster(ComparitorFieldCB.Text, ComparitorCB.Text)

    'End Sub

    'Private Sub CompareMaster(CField As String, CFunction As String)
    '    Dim Value1 As Integer = Nothing
    '    Dim Value2 As Integer = Nothing
    '    Dim Value3 As Integer = Nothing

    '    Dim Rel1 As String = "NUL"
    '    Dim Rel2 As String = "NUL"
    '    Dim PassTest1 As Boolean = True
    '    Dim PassTest2 As Boolean = True

    '    'If Not (DGV1.Rows(0).Cells("F1F2").Value & "" = "") Then
    '    '    MsgBox("fucker|")
    '    '  DGV1.Sort(DGV1.Columns("GPrimaryFilename"), System.ComponentModel.ListSortDirection.Descending)
    '    'End If
    '    ProgressPanel.Show()


    '    OperationLB.Text = "Completing compare process...."
    '    PB1.Minimum = 0
    '    PB1.Maximum = DGV1.Rows.Count
    '    Dim count As Integer = 0

    '    For Each row As DataRow In _MainDT.Rows
    '        Debug.WriteLine("------------------------------------------")
    '        Debug.WriteLine("DGV Row: " & row.Item("GPrimaryFilename").Value.ToString)

    '        Select Case CField
    '            Case "Width"
    '                ' Debug.WriteLine("Width")
    '                Value1 = IntNullficator(row.Item("F1Width"))
    '                Value2 = IntNullficator(row.Item("F2Width"))
    '                Value3 = IntNullficator(row.Item("F3Width"))
    '            Case "Height"
    '                Debug.WriteLine("Height")
    '                Value1 = IntNullficator(row.Item("F1Height"))
    '                Value2 = IntNullficator(row.Item("F2Height"))
    '                Value3 = IntNullficator(row.Item("F3Height"))

    '        End Select


    '        Debug.WriteLine("Values: {0}, {1}, {2}", Value1, Value2, Value3)

    '        Rel1 = Relation(Value1, Value2)
    '        row.Item("F1F2Rel") = Rel1
    '        PassTest1 = TestPassed(Rel1, CFunction)
    '        row.Item("F1Flag") = (Not (PassTest1)).ToString
    '        Debug.WriteLine("1>2: {0}, {1}", Rel1, PassTest1.ToString)

    '        Rel2 = Relation(Value2, Value3)
    '        row.Item("F2F3Rel") = Rel2
    '        PassTest2 = TestPassed(Rel2, CFunction)
    '        row.Item("F2Flag") = (Not (PassTest2)).ToString
    '        Debug.WriteLine("2>3: {0}, {1}", Rel2, PassTest2.ToString)

    '        count = count + 1
    '        PB1.Value = count
    '        Application.DoEvents()



    '    Next

    '    MsgBox("Continue...")
    '    '_MainDT.Columns.Add("F1Width")
    '    '_MainDT.Columns.Add("F1Height")
    '    '_MainDT.Columns.Add("F1Size")
    '    '_MainDT.Columns.Add("F1Flag", GetType(Boolean))
    '    '_MainDT.Columns.Add("F1F2Rel", GetType(String))
    '    DGV1_PopulateIMg(Nothing, Nothing)

    '    ' DGV1.Sort(DGV1.Columns("F1Flag"), System.ComponentModel.ListSortDirection.Descending)

    '    ProgressPanel.Hide()

    'End Sub


    Private Sub HighlightBT_Click(sender As Object, e As EventArgs) Handles HighlightBT.Click
        Debug.WriteLine(vbCr & "======= Highlight Proceedure =========")
        Debug.WriteLine("Comparitor Field: " & ComparitorFieldCB.Text)
        Debug.WriteLine("Comparitor Function: " & ComparitorCB.Text)
        ' HighlightMaster(ComparitorFieldCB.Text, ComparitorCB.Text, ComparitorFoldersCB.Text)
        If My.Settings.HIghlight = False Then

            My.Settings.HIghlight = True
            HighlightBT.BackColor = Color.Orange
            My.Settings.Save()
            DGV1.Refresh()
        Else
            My.Settings.HIghlight = False
            HighlightBT.BackColor = DefaultBackColor
            My.Settings.Save()
            DGVRedrawFlag = True
            DGV1.Invalidate()
            '  DGV1.DataSource = Nothing
            ' DGV1.DataSource = _MainDT
            DGVRedrawFlag = False
            'setupDGV()
        End If

    End Sub




    Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DGV1.CellFormatting
        ' Debug.WriteLine("=================== DGV REDRAW =======================")
        If My.Settings.HIghlight = True Then
            If e.ColumnIndex = F1Col Then

                'Debug.WriteLine(vbCr & "======= Highlight Proceedure =========")
                'Debug.WriteLine("Row,col,bgcol,value: {0},{1},{2},{3}", e.RowIndex, e.ColumnIndex, e.CellStyle.BackColor, e.Value)

                Dim rel As Integer = 0

                rel = (IntNullficator(e.Value)).CompareTo(IntNullficator(DGV1.Rows(e.RowIndex).Cells(F2Col).Value))

                Select Case HLOprtr
                    Case "EQU"
                        If rel = 0 Then
                            e.CellStyle.BackColor = HighlighCol
                            ' DGV1.Rows(e.RowIndex).Cells(F2Col).Style.BackColor = HighlighCol
                        Else
                            e.CellStyle.BackColor = DGV1.Columns(e.ColumnIndex).DataGridView.ColumnHeadersDefaultCellStyle.BackColor
                            ' DGV1.Rows(e.RowIndex).Cells(F2Col).Style.BackColor = DefaultBackColor
                        End If
                    Case "GEQ"
                        If rel = 0 Or rel = 1 Then
                            e.CellStyle.BackColor = HighlighCol
                            ' DGV1.Rows(e.RowIndex).Cells(F2Col).Style.BackColor = HighlighCol
                            Debug.WriteLine("HIGHLILGHT!: {0},{1},{2},{3}", e.RowIndex, e.ColumnIndex, e.CellStyle.BackColor, e.Value)
                        Else
                            '   e.CellStyle.BackColor
                            ' e.CellStyle.BackColor = DGV1.Columns(e.ColumnIndex).DataGridView.ColumnHeadersDefaultCellStyle.BackColor
                            '  DGV1.Rows(e.RowIndex).Cells(F2Col).Style.BackColor = DefaultBackColor
                            Debug.WriteLine("RESET!: {0},{1},{2},{3}", e.RowIndex, e.ColumnIndex, e.CellStyle.BackColor, e.Value)

                        End If
                    Case "LEQ"
                        If rel = 0 Or rel = -1 Then
                            e.CellStyle.BackColor = HighlighCol
                            '   DGV1.Rows(e.RowIndex).Cells(F2Col).Style.BackColor = HighlighCol
                        Else
                            '  e.CellStyle.BackColor = DGV1.Columns(e.ColumnIndex).DataGridView.DefaultCellStyle.BackColor

                        End If
                    Case "GTT"
                        If rel = 1 Then
                            e.CellStyle.BackColor = HighlighCol
                            '    DGV1.Rows(e.RowIndex).Cells(F2Col).Style.BackColor = HighlighCol
                        Else
                            ' e.CellStyle.BackColor = DGV1.Columns(e.ColumnIndex).DataGridView.DefaultCellStyle.BackColor
                            '    DGV1.Rows(e.RowIndex).Cells(F2Col).Style.BackColor = DefaultBackColor
                        End If
                    Case "LST"
                        If rel = -1 Then
                            e.CellStyle.BackColor = HighlighCol
                            '     DGV1.Rows(e.RowIndex).Cells(F2Col).Style.BackColor = HighlighCol
                        Else
                            ' e.CellStyle.BackColor = DGV1.Columns(e.ColumnIndex).DataGridView.DefaultCellStyle.BackColor

                            'DGV1.Rows(e.RowIndex).Cells(F2Col).Style.BackColor = DefaultBackColor
                        End If
                    Case "NEQ"
                        If rel = 1 Or rel = -1 Then
                            e.CellStyle.BackColor = HighlighCol
                            '   DGV1.Rows(e.RowIndex).Cells(F2Col).Style.BackColor = HighlighCol
                        Else

                            'e.CellStyle.BackColor = DGV1.Columns(e.ColumnIndex).DataGridView.DefaultCellStyle.BackColor
                        End If
                End Select
            ElseIf e.ColumnIndex = F2Col Then
                'Debug.WriteLine("F2 Triggered: {0},{1},{2},{3}", e.RowIndex, e.ColumnIndex, e.CellStyle.BackColor, e.Value)
                'Debug.WriteLine(DGV1.Rows(e.RowIndex).Cells(F1Col).Style.BackColor)
                'If DGV1.Rows(e.RowIndex).Cells(F1Col).Style.BackColor = HighlighCol Then
                '    ' MsgBox("here")
                '    e.CellStyle.BackColor = HighlighCol
                'Else
                '    e.CellStyle.BackColor = DefaultBackColor
                'End If
                'e.CellStyle.BackColor = DefaultBackColor
            Else
                'Check for detrius 
                'If e.CellStyle.BackColor = HighlighCol Then
                '    e.CellStyle.BackColor = DefaultBackColor
                'End If
            End If
        Else
            'If DGVRedrawFlag = True Then
            '    Debug.WriteLine("HERE!")
            '    If e.CellStyle.BackColor = HighlighCol Then
            '        e.CellStyle.BackColor = DefaultBackColor
            '    End If
            'End If
        End If


    End Sub

    Private Sub BW1_Highlighting(ByVal sender As System.Object, _
             ByVal e As System.ComponentModel.DoWorkEventArgs) _
             Handles BW1.DoWork



    End Sub

    Private Sub BW1_HLFinished(ByVal sender As System.Object, _
             ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
             Handles BW1.RunWorkerCompleted
        MsgBox("Highligting finished: " & e.Result.ToString)
    End Sub

    Private Sub HighlightMaster(CField As String, CFunction As String, folders As String)
        Dim Value1 As Integer = Nothing
        Dim Value2 As Integer = Nothing
        Dim Value3 As Integer = Nothing

        Dim Rel1 As String = "NUL"
        Dim Rel2 As String = "NUL"
        Dim PassTest1 As Boolean = True
        Dim PassTest2 As Boolean = True

        DGV1.GetType.InvokeMember("DoubleBuffered", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.SetProperty, Nothing, DGV1, New Object() {True})

        'If Not (DGV1.Rows(0).Cells("F1F2").Value & "" = "") Then
        '    MsgBox("fucker|")
        '  DGV1.Sort(DGV1.Columns("GPrimaryFilename"), System.ComponentModel.ListSortDirection.Descending)
        'End If
        ProgressPanel.Show()
        '  DGV1.SuspendLayout()

        OperationLB.Text = "Completing compare process...."
        PB1.Minimum = 0
        PB1.Maximum = DGV1.Rows.Count
        Dim count As Integer = 0




        For Each row As DataGridViewRow In DGV1.Rows
            Debug.WriteLine("------------------------------------------")
            Debug.WriteLine("DGV Row: " & row.Cells("GPrimaryFilename").Value.ToString)

            Select Case CField
                Case "Width"
                    ' Debug.WriteLine("Width")
                    Value1 = IntNullficator(row.Cells("F1Width").Value)
                    Value2 = IntNullficator(row.Cells("F2Width").Value)
                    Value3 = IntNullficator(row.Cells("F3Width").Value)
                Case "Height"
                    Debug.WriteLine("Height")
                    Value1 = IntNullficator(row.Cells("F1Height").Value)
                    Value2 = IntNullficator(row.Cells("F2Height").Value)
                    Value3 = IntNullficator(row.Cells("F3Height").Value)
            End Select

            'Debug.WriteLine("Values: {0}, {1}, {2}", Value1, Value2, Value3)
            'Debug.WriteLine("Evaluate: " & Value1.CompareTo(Value2))
            '-1 = < , 0 = equ, 1 = >

            Select Case folders
                Case "Grey and Blue"
                    'Rel1 = Relation(Value1, Value2)
                    '' row.Cells("F1F2Rel").Value = Rel1
                    'PassTest1 = TestPassed(Rel1, CFunction)
                    row.Cells("F1" & CField).Style.BackColor = Color.Red
                    row.Cells("F2" & CField).Style.BackColor = Color.Red
                    Debug.WriteLine("1>2: {0}, {1}", Rel1, PassTest1.ToString)

                Case "Blue and Green"
                    Rel2 = Relation(Value2, Value3)
                    'row.Cells("F2F3Rel").Value = Rel2
                    PassTest2 = TestPassed(Rel2, CFunction)
                    row.Cells("F2" & CField).Style.BackColor = Color.Red
                    row.Cells("F3" & CField).Style.BackColor = Color.Red
                    Debug.WriteLine("2>3: {0}, {1}", Rel2, PassTest2.ToString)

            End Select





            count = count + 1
            PB1.Value = count
            Application.DoEvents()



        Next

        MsgBox("Continue...")
        '_MainDT.Columns.Add("F1Width")
        '_MainDT.Columns.Add("F1Height")
        '_MainDT.Columns.Add("F1Size")
        '_MainDT.Columns.Add("F1Flag", GetType(Boolean))
        '_MainDT.Columns.Add("F1F2Rel", GetType(String))
        ' DGV1_PopulateIMg(Nothing, Nothing)

        ' DGV1.Sort(DGV1.Columns("F1Flag"), System.ComponentModel.ListSortDirection.Descending)

        ProgressPanel.Hide()
        ' DGV1.ResumeLayout()

    End Sub




    Public Shared Function NotNull(Of T)(ByVal Value As T, ByVal DefaultValue As T) As T
        If Value Is Nothing OrElse IsDBNull(Value) Then
            Return DefaultValue
        Else
            Return Value
        End If
    End Function

    Private Function RelImage(Rel As String, TestPass As Boolean) As Image
        Select Case Rel
            Case "NUL"
                Return My.Resources.ZeroGood
            Case "EQU"
                If TestPass Then
                    Return My.Resources.EqGood
                Else
                    Return My.Resources.EqBad
                End If
            Case "LST"
                If TestPass Then
                    Return My.Resources.LSGood
                Else
                    Return My.Resources.LSBad
                End If
            Case "GTT"
                If TestPass Then
                    Return My.Resources.GTGood
                Else
                    Return My.Resources.GTBad
                End If
        End Select
        Return My.Resources.NEQBad
    End Function

    Private Function TestPassed(Rel As String, Test As String) As Boolean
        'Debug.WriteLine("Test Passed Sub. Rel, Test: {0}, {1}", Rel, Test)
        If Rel = "NUL" Then Return True
        Select Case Test
            Case "EQU"
                If Rel = "EQU" Then Return True
            Case "LEQ"
                If Rel = "EQU" Or Rel = "LST" Then Return True
            Case "GEQ"
                If Rel = "EQU" Or Rel = "GTT" Then Return True
            Case "GTT"
                If Rel = "GTT" Then Return True
            Case "LST"
                If Rel = "LST" Then Return True
            Case "NEQ"
                If Rel <> "EQU" Then Return True
        End Select
        Debug.WriteLine("Must be false.....")
        Return False
    End Function

    Private Function Relation(Value1 As Integer, Value2 As Integer) As String
        If Value1 = -1 Or Value2 = -1 Then Return "NUL"
        If Value1 < Value2 Then Return "LST"
        If Value1 > Value2 Then Return "GTT"
        If Value1 = Value2 Then Return "EQU"

        Debug.WriteLine("Bombed out...")
        Return "EQU"
    End Function

    Private Function IntNullficator(val As Object) As Integer
        'Dim convertInteger As Integer
        Try
            If IsDBNull(val) Then
                IntNullficator = -1
            Else
                IntNullficator = val
            End If
        Catch ex As Exception
            IntNullficator = -1
        End Try
        'Return convertInteger
    End Function



    Private Sub DGV1_Sorted(sender As Object, e As EventArgs) Handles DGV1.Sorted
        DGV1_PopulateIMg(Nothing, Nothing)
    End Sub

    Private Sub DGV1_PopulateIMg(sender As Object, e As EventArgs)

        'Dim rel1 As String
        'Dim rel2 As String
        'Dim passtest1 As Boolean
        'Dim passtest2 As Boolean

        'For Each row As DataGridViewRow In DGV1.Rows
        '    rel1 = row.Cells("F1F2Rel").Value
        '    passtest1 = Not (row.Cells("F1Flag").Value)
        '    row.Cells("F1F2").Value = RelImage(rel1, passtest1)

        '    rel2 = row.Cells("F2F3Rel").Value
        '    passtest2 = Not (row.Cells("F2Flag").Value)
        '    row.Cells("F2F3").Value = RelImage(rel2, passtest2)

        'Next
        'DGV1.Columns("F1F2").Width = 32
        'DGV1.Columns("F2F3").Width = 32

    End Sub

    Private Sub DG1_HeaderClicked(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DGV1.ColumnHeaderMouseClick
        If DGV1.Columns(e.ColumnIndex).HeaderText = "F1F2" Then
            Dim sortdir As System.ComponentModel.ListSortDirection
            If LastRelSort = System.ComponentModel.ListSortDirection.Ascending Then
                sortdir = System.ComponentModel.ListSortDirection.Descending
                LastRelSort = System.ComponentModel.ListSortDirection.Descending
            Else
                sortdir = System.ComponentModel.ListSortDirection.Ascending
                LastRelSort = System.ComponentModel.ListSortDirection.Ascending
            End If
            DGV1.Sort(DGV1.Columns("F1F2Rel"), sortdir)
        End If

        If DGV1.Columns(e.ColumnIndex).HeaderText = "F2F3" Then
            Dim sortdir As System.ComponentModel.ListSortDirection
            If LastRelSort = System.ComponentModel.ListSortDirection.Ascending Then
                sortdir = System.ComponentModel.ListSortDirection.Descending
                LastRelSort = System.ComponentModel.ListSortDirection.Descending
            Else
                sortdir = System.ComponentModel.ListSortDirection.Ascending
                LastRelSort = System.ComponentModel.ListSortDirection.Ascending
            End If
            DGV1.Sort(DGV1.Columns("F2F3Rel"), sortdir)
        End If

    End Sub

    Private Sub Initialise_DGV()

        OperationLB.Text = "Populating default images in DGV...."
        PB1.Minimum = 0
        PB1.Maximum = DGV1.Rows.Count
        Dim count As Integer = 0


        For Each row As DataGridViewRow In DGV1.Rows
            row.Cells("F1F2").Value = My.Resources.question_mark_icon
            row.Cells("F2F3").Value = My.Resources.question_mark_icon
            row.Cells("F1F2Rel").Value = "EQU"
            row.Cells("F2F3Rel").Value = "EQU"
            row.Cells("F1Flag").Value = "False"
            row.Cells("F2Flag").Value = "True"

            count = count + 1
            PB1.Value = count
            Application.DoEvents()

        Next
    End Sub


    Private Sub SortF1PB_Click(sender As Object, e As EventArgs)
        DGV1.Sort(DGV1.Columns("F1Flag"), System.ComponentModel.ListSortDirection.Descending)
    End Sub


    Private Sub SortF2PB_Click(sender As Object, e As EventArgs)
        DGV1.Sort(DGV1.Columns("F2Flag"), System.ComponentModel.ListSortDirection.Descending)
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs)
        Dim dv As DataView = New DataView(_MainDT)
        dv.RowFilter = "F1Width = F2Width"
        'Dim query = _GSMDS.Tables(0).Rows.Where(Function(dr) dr("F1Width").ToString = dr("F2Width").ToString).ToArray()
        DGV1.DataSource = dv
    End Sub


    Private Sub GoCompareBT_Click(sender As Object, e As EventArgs) Handles GoCompareBT.Click
        Debug.WriteLine(vbCr & "================ FILTER ===================")

        Select Case Filtered

            Case True
                Debug.WriteLine("Flitered=true. Back to MainDT")
                DGV1.DataSource = _MainDT
                Filtered = False
                setupDGV()

                ' ComparitorFieldCB.SelectedIndex = 0

            Case False

                Debug.WriteLine("Flitered=false. Do filter routine")
                TabControl1.Enabled = False
                Me.Cursor = Cursors.WaitCursor

                'check datatable has data/ loaded
                If _MainDT.Rows.Count = 0 Then Return

                Dim Folders As String = ComparitorFoldersCB.Text
                Dim Oprtor As String = ComparitorCB.Text
                Dim Field As String = ComparitorFieldCB.Text

                Dim Filter As String = ""


                'DGV1.DataSource = _MainDT
                'DGV1.Refresh()

                'Contruct Filter String
                Dim Field1 As String = ""
                Dim Field2 As String = ""
                Dim Compr As String = " = "
                Dim Compr2 As String = ""

                Select Case Folders
                    Case "Gray and Blue"
                        Field1 = "F1"
                        Field2 = "F2"
                    Case "Blue and Green"
                        Field1 = "F2"
                        Field2 = "F3"
                    Case "Gray and Green"
                        Field1 = "F1"
                        Field2 = "F3"
                End Select

                Select Case Field
                    Case "Width"
                        Field1 = Field1 & "Width"
                        Field2 = Field2 & "Width"
                    Case "Height"
                        Field1 = Field1 & "Height"
                        Field2 = Field2 & "Height"
                    Case "Size"
                        Field1 = Field1 & "Size"
                        Field2 = Field2 & "Size"
                    Case "No Filter"
                        Field1 = ""
                        Field2 = ""
                End Select

                Select Case Oprtor
                    Case "EQU"
                        Compr = " = "

                    Case "GEQ"
                        Compr = " >= "
                    Case "LEQ"
                        Compr = " <= "
                    Case "GTT"
                        Compr = " > "
                    Case "LST"
                        Compr = " < "
                    Case "NEQ"
                        Compr = " <> "
                End Select



                Filter = Field1 & Compr & Field2

                Debug.WriteLine("F1, F2 + filer: [{0]}], [{1}], [{2}]")

                If Field = "No Filter" Then
                    DGV1.DataSource = _MainDT
                    ComparitorFieldCB.SelectedIndex = 0
                    Debug.WriteLine("No Filter Used - return full grid...")
                Else
                    Debug.WriteLine(vbCr & "Final Filter: " & Filter)
                    Dim dv As DataView = New DataView(_MainDT)
                    dv.RowFilter = Filter
                    DGV1.DataSource = dv
                End If




                'Outline cloumns
                setupDGV()

                If Field1 <> "" Then
                    DGV1.Columns(Field1).DefaultCellStyle.BackColor = Color.Thistle
                    'DGV1.Columns(Field1).DataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Thistle
                End If
                If Field2 <> "" Then
                    DGV1.Columns(Field2).DefaultCellStyle.BackColor = Color.Thistle
                    'DGV1.Columns(Field2).DataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Thistle
                End If

                Filtered = True

                TabControl1.Enabled = True
                Me.Cursor = Cursors.Default

        End Select


    End Sub


    Private Sub NewDT_Click(sender As Object, e As EventArgs) Handles NewDT.Click
        If SetupCB.Text = "" Then Return

        Dim newrow As DataRow
        Dim DoNewRow As Boolean = True

        For Each row As DataRow In _KeepDS.Tables("Setups").Rows
            If row.Item("Name") = SetupCB.Text Then
                Debug.WriteLine("HERE!")
                If MsgBox("Update this existing Setup?", MsgBoxStyle.YesNo, "Setup Already Exists") = MsgBoxResult.Yes Then 'if you select yes in the msgbox then it will close the window
                    newrow = row
                    DoNewRow = False
                Else
                    Return
                End If
            End If
        Next

        If DoNewRow = True Then
            If MsgBox("Create a new Setup?", MsgBoxStyle.YesNo, "No Setup exists of this name..") = MsgBoxResult.Yes Then 'if you select yes in the msgbox then it will close the window
                newrow = _KeepDS.Tables("Setups").NewRow
                SetupCB.Items.Add(SetupCB.Text)
            Else
                Return
            End If
        End If



        UpdateSetupRecord(newrow, DoNewRow)

        SaveDataset()

    End Sub

    Private Sub UpdateSetupRecord(newrow As DataRow, DoNewRow As Boolean)

        newrow("NewTitle") = NewTB.Text
        newrow("NewFolder") = FPNew.Tag
        newrow("LocalTitle") = LocalTB.Text
        newrow("LocalFolder") = FPLocal.Tag
        newrow("CloudTitle") = CloudTB.Text
        newrow("CloudFolder") = FPCloud.Tag
        newrow("ResizeTitle") = ResizeTB.Text
        newrow("ResizeFolder") = FPResize.Tag
        newrow("DatTitle") = DatTB.Text
        newrow("DATFile") = FPDat.Tag
        newrow("Name") = SetupCB.Text
        newrow("System") = SystemsCB.Text
        newrow("FilenameCol") = GameColumnTB.Text

        If DefaultChB.Checked Then
            For Each row As DataRow In _KeepDS.Tables("Setups").Rows
                row.Item("startup") = False
            Next
            newrow("startup") = True
        End If

        If DoNewRow Then
            _KeepDS.Tables("Setups").Rows.Add(newrow)
        End If

    End Sub


    Private Sub SetupCB_SelectedIndexChanged(sender As Object, e As EventArgs) Handles SetupCB.SelectedIndexChanged
        Dim selrow() As DataRow
        selrow = _KeepDS.Tables("Setups").Select("Name = '" & SetupCB.Text & "'")
        If selrow.Length = 0 Then Return

        log.Log_Data(SetupCB.Text, "SetupCB changed to")

        PopulateSetup(selrow(0).Item("ID"))

    End Sub


    Private Sub ClearBT_Click(sender As Object, e As EventArgs) Handles ClearBT.Click
        PopDefaultSetup()
    End Sub

    Private Sub HideGamenameChB_CheckedChanged(sender As Object, e As EventArgs)
        'If HideGamenameChB.Checked Then
        '    My.Settings.HideGameName = True
        '    If DGV1.Columns.Contains("GGameName") Then DGV1.Columns("GGameName").Visible = False
        'Else
        '    My.Settings.HideGameName = False
        '    If DGV1.Columns.Contains("GGameName") Then DGV1.Columns("GGameName").Visible = True
        'End If
    End Sub

    Private Sub ShowFullInfoChB_CheckedChanged(sender As Object, e As EventArgs) Handles ShowFullInfoChB.CheckedChanged
        If ShowFullInfoChB.Checked Then
            My.Settings.ShowFullInfo = True
            If DGV1.Columns.Contains("F1BitDepth") Then
                DGV1.Columns("F1BitDepth").Visible = True
                DGV1.Columns("F1VPPi").Visible = True
                DGV1.Columns("F1HPPi").Visible = True
                DGV1.Columns("F1Readonly?").Visible = True
                DGV1.Columns("F1DateLastSaved").Visible = True
                DGV1.Columns("F1DateCreated").Visible = True
                DGV1.Columns("F1DateAccessed").Visible = True
                DGV1.Columns("F2BitDepth").Visible = True
                DGV1.Columns("F2VPPi").Visible = True
                DGV1.Columns("F2HPPi").Visible = True
                DGV1.Columns("F2Readonly?").Visible = True
                DGV1.Columns("F2DateLastSaved").Visible = True
                DGV1.Columns("F2DateCreated").Visible = True
                DGV1.Columns("F2DateAccessed").Visible = True
                DGV1.Columns("F3BitDepth").Visible = True
                DGV1.Columns("F3VPPi").Visible = True
                DGV1.Columns("F3HPPi").Visible = True
                DGV1.Columns("F3Readonly?").Visible = True
                DGV1.Columns("F3DateLastSaved").Visible = True
                DGV1.Columns("F3DateCreated").Visible = True
                DGV1.Columns("F3DateAccessed").Visible = True
            End If
        Else
            My.Settings.ShowFullInfo = False
            If DGV1.Columns.Contains("F1BitDepth") Then
                DGV1.Columns("F1BitDepth").Visible = False
                DGV1.Columns("F1VPPi").Visible = False
                DGV1.Columns("F1HPPi").Visible = False
                DGV1.Columns("F1Readonly?").Visible = False
                DGV1.Columns("F1DateLastSaved").Visible = False
                DGV1.Columns("F1DateCreated").Visible = False
                DGV1.Columns("F1DateAccessed").Visible = False
                DGV1.Columns("F2BitDepth").Visible = False
                DGV1.Columns("F2VPPi").Visible = False
                DGV1.Columns("F2HPPi").Visible = False
                DGV1.Columns("F2Readonly?").Visible = False
                DGV1.Columns("F2DateLastSaved").Visible = False
                DGV1.Columns("F2DateCreated").Visible = False
                DGV1.Columns("F2DateAccessed").Visible = False
                DGV1.Columns("F3BitDepth").Visible = False
                DGV1.Columns("F3VPPi").Visible = False
                DGV1.Columns("F3HPPi").Visible = False
                DGV1.Columns("F3Readonly?").Visible = False
                DGV1.Columns("F3DateLastSaved").Visible = False
                DGV1.Columns("F3DateCreated").Visible = False
                DGV1.Columns("F3DateAccessed").Visible = False
            End If

        End If
    End Sub

    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles SettsWinStateCB.CheckedChanged
        If SettsWinStateCB.Checked = True Then
            My.Settings.PrevWinState = True
        Else
            My.Settings.PrevWinState = False
        End If
    End Sub

    Private Sub SettsBUOWsCB_CheckedChanged(sender As Object, e As EventArgs) Handles SettsBUOWsCB.CheckedChanged
        If SettsBUOWsCB.Checked = True Then
            My.Settings.BackupOWs = True
        Else
            My.Settings.BackupOWs = False
        End If
        My.Settings.Save()
    End Sub

    Private Sub SettsKeepLastCB_CheckedChanged(sender As Object, e As EventArgs) Handles SettsKeepLastCB.CheckedChanged
        If SettsKeepLastCB.Checked = True Then
            My.Settings.JustKeepLast = True
        Else
            My.Settings.JustKeepLast = False
        End If
        My.Settings.Save()
    End Sub

    Private Sub MoveFile(filename As String, ext As String, source As String,
                         destination As String, BUOverride As Boolean,
                         folder1 As String, folder2 As String, GameID As Integer)
        Debug.WriteLine("MoveFile. filename: " & filename)
        Debug.WriteLine("MoveFile. SaveAs: " & My.Settings.FileUseDBName)
        'Check Source file exists...
        If Not (File.Exists(source & "\" & filename)) Then
            Debug.WriteLine(vbCr & "Source file deosn't exist <<<<<<<<<<<<<")
            Return
        End If

        If My.Settings.SaveAsPng = True Then
            ext = ".png"
        End If

        Dim DestFile As String = filename
        If UseFilenameTG.Tag = "true" Then
            DestFile = SafeFilename(FuzzyTB.Text & ext)
        ElseIf My.Settings.FileUseDBName = "Database GameName" Then
            Debug.WriteLine("SaveAs GameName")
            Dim grow() As DataRow = _MainDT.Select("GID= '" & GameID & "'")
            DestFile = SafeFilename(grow(0).Item("GGameName") & ext)
            Debug.WriteLine("Resulting DestFile: " & DestFile)
        ElseIf My.Settings.FileUseDBName = "Database FileName" Then
            Dim grow() As DataRow = _MainDT.Select("GID= '" & GameID & "'")
            DestFile = SafeFilename(grow(0).Item("GPrimaryFilename") & ext)
        End If

        '_MainDT.Columns.Add("GGameName")
        '_MainDT.Columns.Add("GPrimaryFilename") ' - Used as IMage filename

        'BACKUP Process first...
        'First check if BUs enabled, if folder exists
        If My.Settings.BackupOWs = True Or BUOverride = True Then
            If File.Exists(destination & "\" & filename) Then
                If Not (My.Computer.FileSystem.DirectoryExists(destination & "\Overwrites")) Then
                    System.IO.Directory.CreateDirectory(destination & "\Overwrites")
                End If
                Dim BUFilename As String = ""
                If My.Settings.JustKeepLast = True And BUOverride <> True Then
                    BUFilename = SafeFilename(filename)
                Else
                    BUFilename = Path.GetFileNameWithoutExtension(SafeFilename(filename)) & DateTime.Now.ToString("_ddMMyy_HH.mm.ss") & ext
                End If
                My.Computer.FileSystem.CopyFile(
                        destination & "\" & filename,
                        destination & "\Overwrites\" & BUFilename,
                        Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
                        Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
            End If
        End If

        'Now update DT - eeep
        Dim row() As DataRow = _MainDT.Select("GID= '" & GameID & "'")
        row(0).Item("F" & folder2 & "FileName") = DestFile
        row(0).Item("F" & folder2 & "Width") = row(0).Item("F" & folder1 & "Width")
        row(0).Item("F" & folder2 & "Height") = row(0).Item("F" & folder1 & "Height")
        row(0).Item("F" & folder2 & "Size") = row(0).Item("F" & folder1 & "Size")
        row(0).Item("F" & folder2 & "Ext") = ext
        row(0).Item("F" & folder2 & "BitDepth") = row(0).Item("F" & folder1 & "BitDepth")
        row(0).Item("F" & folder2 & "VPPi") = row(0).Item("F" & folder1 & "VPPi")
        row(0).Item("F" & folder2 & "HPPi") = row(0).Item("F" & folder1 & "HPPi")
        row(0).Item("F" & folder2 & "Readonly?") = row(0).Item("F" & folder1 & "Readonly?")
        row(0).Item("F" & folder2 & "DateLastSaved") = row(0).Item("F" & folder1 & "DateLastSaved")
        row(0).Item("F" & folder2 & "DateCreated") = row(0).Item("F" & folder1 & "DateCreated")
        row(0).Item("F" & folder2 & "DateAccessed") = row(0).Item("F" & folder1 & "DateAccessed")

        'Then Copy file



        Dim finalout As String = source & "\" & filename
        If My.Settings.SaveAsPng = True Then
            finalout = ConvertedToPng(finalout)
        End If

        If File.Exists(destination & Path.GetFileName(finalout)) And My.Settings.KillBatch = False Then
            Dim result As DialogResult = MessageBox.Show("The target of the copy already contains a file called: " & vbCr & vbCr & Path.GetFileName(finalout) & vbCr & vbCr & "Do you want to overwrite the existing file?",
                                                    "Overwrite file?", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation)
            If result = Windows.Forms.DialogResult.No Then Return
        End If

        My.Computer.FileSystem.CopyFile(
                finalout,
                destination & "\" & DestFile,
                Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
                Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)

    End Sub

    Private Function ConvertedToPng(source As String) As String

        Debug.WriteLine("Convert to png function")
        If Path.GetExtension(source) = "png" Then
            Debug.WriteLine("file already png")
            Return source
        Else
            Dim newimg As String = Path.GetTempPath & "ImgConvertedPng.png"
            Debug.WriteLine("making new png file and updating vars")
            ConvertImage(source, ImageFormat.Png, newimg)
            Return newimg
        End If

    End Function


    Private Sub Grey2BlueBT_Click(sender As Object, e As EventArgs) Handles Grey2BlueBT.Click
        'pass which folders...
        FileMoveMacinator(_NewItemsFolder, _LocalItemsFolder, "F1Ext", False, "1", "2")
    End Sub

    Private Sub FileMoveMacinator(source As String, destination As String,
                                  ExtField As String, BUOverride As Boolean,
                                  folder1 As String, folder2 As String)

        If DGV1.CurrentCell Is Nothing Then
            Return
        End If

        If BatchCopyCB.Checked = False Then
            'SINGLE INSTANCE
            'Check Source file in existence
            If (DGV1.CurrentRow.Cells("F" & folder1 & "Ext").Value & "" <> "") Then

                MoveFile(DGV1.CurrentRow.Cells("F" & folder1 & "FileName").Value,
                         DGV1.CurrentRow.Cells(ExtField).Value,
                         source, destination, BUOverride,
                         folder1, folder2, DGV1.CurrentRow.Cells("GID").Value)
            Else
                Return
            End If
        Else
            'BATCH JOB
            Debug.WriteLine(vbCr & "============== BATCH JOB ===================")
            If My.Settings.KillBatch = False Then
                If MsgBox("Batch copy selected. Are you sure you want to continue copying and overwriting all files?", MsgBoxStyle.YesNo, "Batch Copy Selected") = MsgBoxResult.No Then
                    ProgressPanel.Hide()
                    Me.Cursor = Cursors.Default
                    TabControl1.Enabled = True
                    Return
                End If
            End If

            'DGV1.Visible = False

            'Disable and progress bar:
            ProgressPanel.Show()
            Me.Cursor = Cursors.WaitCursor
            TabControl1.Enabled = False
            Dim numrecs As Integer = _MainDT.Select("Sel = True").Count
            OperationLB.Text = "Moving selected files (" & numrecs & " files)"
            PB1.Minimum = 0
            PB1.Maximum = numrecs
            Dim count As Integer = 0


            For Each row As DataRow In _MainDT.Select("Sel = True")
                Debug.WriteLine("Game: " & row.Item("GID").ToString &
                                ". " & row.Item("F" & folder1 & "FileName").ToString)
                If (row.Item("F" & folder1 & "Ext") & "" <> "") Then

                    MoveFile(row.Item("F" & folder1 & "FileName") & "",
                         row.Item(ExtField) & "",
                         source, destination, BUOverride,
                         folder1, folder2, row.Item("GID") & "")

                    'REF:
                    'MoveFile(DGV1.CurrentRow.Cells("F" & folder1 & "FileName").Value,
                    '    DGV1.CurrentRow.Cells(ExtField).Value,
                    '    source, destination, BUOverride,
                    '    folder1, folder2, DGV1.CurrentRow.Cells("GID").Value)

                Else
                    Debug.WriteLine("File didn't exist: " & row.Item("GPrimaryFilename").ToString)
                End If

                count = count + 1
                PB1.Value = count
                Application.DoEvents()

            Next
            'DGV1.Visible = True
        End If

        'Refresh images by forcing dgv row enter event
        Try
            Dim dgvrow As DataGridViewRow = DGV1.CurrentRow  ' BLURGH - what a faff
            DGV1.ClearSelection()
            If dgvrow.Index <> 0 Then
                DGV1.CurrentCell = DGV1.Rows(0).Cells(0)
            Else
                DGV1.CurrentCell = DGV1.Rows(DGV1.RowCount - 1).Cells(0)
            End If
            DGV1.CurrentCell = DGV1.Rows(dgvrow.Index).Cells("GGameName")
        Catch
        End Try


        ProgressPanel.Hide()
        Me.Cursor = Cursors.Default
        TabControl1.Enabled = True
        '  My.Computer.Audio.PlaySystemSound(System.Media.SystemSounds.Asterisk)


    End Sub

    Private Function SafeFilename(filen As String) As String
        filen = filen.Replace(":", " -")
        For Each c In IO.Path.GetInvalidFileNameChars
            filen = filen.Replace(c, "")
        Next
        Return filen
    End Function

    Private Sub SortSeldBT_Click(sender As Object, e As EventArgs) Handles SortSeldBT.Click
        DGV1.Sort(DGV1.Columns("Sel"), System.ComponentModel.ListSortDirection.Descending)
    End Sub


    Private Sub SelAllCB_CheckedChanged(sender As Object, e As EventArgs) Handles SelAllCB.CheckedChanged

        Me.Cursor = Cursors.WaitCursor
        TabControl1.Enabled = False

        ProgressPanel.Show()
        OperationLB.Text = "Selecting all in Current View..."
        PB1.Minimum = 0
        PB1.Maximum = DGV1.Rows.Count + 1
        Dim count As Integer = 0

        Dim Toggle As Boolean = SelAllCB.Checked

        DGV1.Columns("Sel").AutoSizeMode = DataGridViewAutoSizeColumnMode.None

        'For Each row As DataRow In DirectCast(DGV1.DataSource, DataTable).Rows

        If TypeOf DGV1.DataSource Is DataView Then
            For Each dvrow As DataRowView In DGV1.DataSource
                Dim row As DataRow = dvrow.Row
                row.Item("Sel") = Toggle
                count = count + 1
                PB1.Value = count
                Application.DoEvents()
            Next
        Else
            For Each row As DataRow In DGV1.DataSource.rows
                row.Item("Sel") = Toggle
                count = count + 1
                PB1.Value = count
                Application.DoEvents()
            Next
        End If


        DGV1.Columns("Sel").AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader


        'For Each row As DataGridViewRow In DGV1.Rows
        '    Debug.WriteLine(row.Cells("GPrimaryFilename"))
        '    row.Cells("Sel").Value = SelAllCB.Checked

        '    count = count + 1
        '    PB1.Value = count
        '    Application.DoEvents()

        'Next

        ProgressPanel.Hide()
        Me.Cursor = Cursors.Default
        TabControl1.Enabled = True

    End Sub

    Private Sub ReviewBT_Click(sender As Object, e As EventArgs) Handles ReviewBT.Click
        DGV1.DataSource = _MainDT
        DGV1.Sort(DGV1.Columns("Sel"), System.ComponentModel.ListSortDirection.Descending)
        DGV1.FirstDisplayedScrollingRowIndex = 0
    End Sub

    Private Sub Button1_Click_1(sender As Object, e As EventArgs)
        'break
    End Sub

    Private Function UnmatchedGames() As Object

        Dim t1 As DataTable = _GSMDS.Tables("Games")
        Dim t2 As DataTable = _MainDT
        Dim Diff = From c In t1 _
                   Group Join d In t2 _
                   On c.Field(Of Integer)("ID") Equals d.Field(Of Integer)("GID") _
                   Into cds = Group From f In cds.DefaultIfEmpty() _
                    Where f Is Nothing
                     Select New With { _
                    .gname = c.Field(Of String)("GameName"), _
                .gfile = c.Field(Of String)("PrimaryFilename"), _
                .gID = c.Field(Of String)("ID")}


        For Each missinggame In Diff
            Debug.WriteLine("Missing: " & missinggame.gname)
        Next

        Return Diff
    End Function



    Private Sub SettsIncUmtchdCB_CheckedChanged(sender As Object, e As EventArgs)
        If SettsIncUmtchdCB.Checked = True Then
            My.Settings.InclUnmatched = True
        Else
            My.Settings.InclUnmatched = False
        End If
    End Sub


    Private Sub RemUnmtchedBT_Click(sender As Object, e As EventArgs)

        Me.Cursor = Cursors.WaitCursor
        TabControl1.Enabled = False
        ProgressPanel.Show()
        OperationLB.Text = "Removing all unmatched games from list..."
        PB1.Minimum = 0
        PB1.Maximum = _MainDT.Rows.Count + 1
        Dim count As Integer = 0



        For i As Integer = _MainDT.Rows.Count - 1 To 0 Step -1
            If _MainDT.Rows(i).Item("NoMatch") Then
                _MainDT.Rows.Remove(_MainDT.Rows(i))
            End If

            count = count + 1
            PB1.Value = count
            Application.DoEvents()

        Next

        '  DGV1.Columns("NoMatch").AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader
        DGV1.DataSource = _MainDT

        ProgressPanel.Hide()
        Me.Cursor = Cursors.Default
        TabControl1.Enabled = True

    End Sub



    Private Sub ListDirBT_Click(sender As Object, e As EventArgs) Handles ListDirBT.Click
        With FBD
            If ListsDirTB.Text = "(none set)" Then
                'MsgBox("nothing!")
            Else
                .SelectedPath = My.Settings.ListDir
            End If
            .Description = "Choose the folder to hold any generated lists...."
        End With
        Dim result As DialogResult = FBD.ShowDialog()
        If result = Windows.Forms.DialogResult.OK Then
            ListsDirTB.Text = CompactString(FBD.SelectedPath, ListsDirTB.Width, ListsDirTB.Font, TextFormatFlags.PathEllipsis)
            My.Settings.ListDir = FBD.SelectedPath
        End If
    End Sub

    Private Sub Unmatched2ListBT_Click(sender As Object, e As EventArgs) Handles Unmatched2ListBT.Click
        If Not My.Computer.FileSystem.DirectoryExists(My.Settings.ListDir) Then
            MsgBox("There's an error with the path for Lists. Please check and set in settings: " & vbCr & My.Settings.ListDir)
            Return
        End If

        If _MainDT.Rows.Count = 0 Then
            MsgBox("You must load the setup first via the Go! button.", MsgBoxStyle.Information)
            Return
        End If

        Dim Filename As String
        Filename = My.Settings.ListDir & "\" & CleanFileName(SetupCB.Text) & "_Missing" & ".txt"

        With SFD
            .AddExtension = True
            .DefaultExt = ".txt"
            .FileName = CleanFileName(SetupCB.Text) & "_Missing" & ".txt"
            .InitialDirectory = My.Settings.ListDir
            .OverwritePrompt = True
            .Title = "Save As..."
            .ValidateNames = True
        End With

        Dim result As DialogResult = SFD.ShowDialog()
        If result = Windows.Forms.DialogResult.OK Then
            Filename = SFD.FileName
        Else
            Return
        End If

        'RemUnmtchedBT_Click(Nothing, Nothing)

        Debug.WriteLine("Final Filename: " & Filename)

        'Dim t1 As DataTable = _GSMDS.Tables("Games")
        'Dim t2 As DataTable = _MainDT
        'Dim Diff = From c In t1 _
        '           Group Join d In t2 _
        '           On c.Field(Of Integer)("ID") Equals d.Field(Of Integer)("GID") _
        '           Into cds = Group From f In cds.DefaultIfEmpty() _
        '            Where f Is Nothing
        '             Select New With { _
        '            .gname = c.Field(Of String)("GameName"), _
        '        .gfile = c.Field(Of String)("PrimaryFilename"), _
        '        .gID = c.Field(Of Int32)("ID")}

        Me.Cursor = Cursors.WaitCursor
        TabControl1.Enabled = False
        ProgressPanel.Show()
        OperationLB.Text = "Writing missing game files list. " & UnmatchedLB.Text & " lines..."
        PB1.Minimum = 0
        PB1.Maximum = CInt(UnmatchedLB.Text) + 1
        Dim count As Integer = 0

        My.Computer.FileSystem.WriteAllText(Filename, "", False)

        Dim file As System.IO.StreamWriter
        file = My.Computer.FileSystem.OpenTextFileWriter(Filename, True)
        file.WriteLine("--------------------------------------------------------")
        file.WriteLine("Run on: " & DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"))
        file.WriteLine("Setup: " & SetupCB.Text)
        file.WriteLine("Total Entries: " & TotalGamesLB.Text)
        file.WriteLine("Matched: " & MatchedLB.Text)
        file.WriteLine("No. of orphans: " & UnmatchedLB.Text)
        file.WriteLine("RomFile Convention: " & GameColumnTB.Text)
        file.WriteLine("--------------------------------------------------------")
        file.WriteLine("Database GameName | Database Filename")
        file.WriteLine("--------------------------------------------------------")

        'For Each missinggame In Diff
        '    file.WriteLine(missinggame.gfile & " :: " & missinggame.gname)
        '    Debug.WriteLine(missinggame.gname)
        '    count = count + 1
        '    PB1.Value = count
        '    Application.DoEvents() 
        'Next

        For Each row As DataRow In _MainDT.Select("NoMatch = true")
            file.WriteLine(row.Item("GGameName") & " | " & row.Item("GPrimaryFilename"))
            count = count + 1
            PB1.Value = count
            Application.DoEvents()
        Next

        file.Close()

        Process.Start(Filename)

        ProgressPanel.Hide()
        Me.Cursor = Cursors.Default
        TabControl1.Enabled = True

    End Sub

    Public Function GetRandomString(ByVal iLength As Integer) As String
        Dim sResult As String = ""
        Dim rdm As New Random()

        For i As Integer = 1 To iLength
            sResult &= ChrW(rdm.Next(32, 126))
        Next

        Return sResult
    End Function

    Private Shared Function CleanFileName(fileName As String) As String
        Return Path.GetInvalidFileNameChars().Aggregate(fileName, Function(current, c) current.Replace(c.ToString(), String.Empty))
    End Function

    Private Sub ListsDirTB_TextChanged(sender As Object, e As EventArgs) Handles ListsDirTB.DoubleClick
        Process.Start("explorer.exe", My.Settings.ListDir)
    End Sub

    Private Sub DGV1_DataSourceChanged(sender As Object, e As EventArgs) Handles DGV1.DataSourceChanged
        'Debug.WriteLine((DGV1.DataSource).GetType.ToString)
        If DGV1.DataSource Is Nothing Then
            GoCompareBT.BackColor = DefaultBackColor
            Return
        End If

        If TypeOf DGV1.DataSource Is System.Data.DataTable Then
            GoCompareBT.BackColor = DefaultBackColor
        Else
            GoCompareBT.BackColor = Color.Orange
        End If
    End Sub




    Private Sub Button4_Click(sender As Object, e As EventArgs)
        With CD1
            .AllowFullOpen = True
            .AnyColor = True
            .Color = My.Settings.HighlightCol
            .FullOpen = True
            .SolidColorOnly = True
        End With
        Dim result As DialogResult = CD1.ShowDialog()
        My.Settings.HighlightCol = CD1.Color
        HighlighCol = CD1.Color
        HLColPB.BackColor = CD1.Color
    End Sub

    Private Sub SettsIncUmtchdCB_CheckedChanged_1(sender As Object, e As EventArgs) Handles SettsIncUmtchdCB.CheckedChanged
        If SettsIncUmtchdCB.Checked = True Then
            My.Settings.InclUnmatched = True
        Else
            My.Settings.InclUnmatched = False
        End If
    End Sub

    Private Sub DGV1_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles DGV1.CellPainting

        'Debug.WriteLine(vbCr & "CellPaint: " & ComparitorCB.SelectedIndex)

        'Imagelist1
        'Image to top left 
        If e.RowIndex < 0 And e.ColumnIndex < 0 Then
            If Filtered = True Then
                e.PaintBackground(e.ClipBounds, True)
                ' e.Graphics.DrawImage(My.Resources.Blue_Green_Flag, e.CellBounds)
                e.Graphics.DrawImage(Me.ImageList1.Images(ComparitorCB.SelectedIndex), e.CellBounds)
                e.Handled = True
            End If
        End If

    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles DelBT.Click
        If SetupCB.Text = "" Then Return
        If MsgBox("Are you sure you want to delete the setup?" & vbCr & SetupName.Text, MsgBoxStyle.YesNo, "Delete Setup?") = MsgBoxResult.No Then
            Return
        End If
        Dim delrow As DataRow = _KeepDS.Tables("Setups").Select("ID = " & SetupID.Text)(0)
        delrow.Delete()
        SetupCB.Items.Remove(SetupName.Text)
        PopDefaultSetup()
        SaveDataset()
    End Sub


    Private Sub Blue2GreenBT_Click(sender As Object, e As EventArgs) Handles Blue2GreenBT.Click
        'BLUE TO GREEN
        FileMoveMacinator(_LocalItemsFolder, _CloudSyncFolder, "F2Ext", False, "2", "3")
        ' Private Sub FileMoveMacinator(source As String, destination As String,
        'ExtField As String, BUOverride As Boolean,
        'folder1 As String, folder2 As String)
    End Sub

    Private Sub Green2BlueBT_Click(sender As Object, e As EventArgs) Handles Green2BlueBT.Click
        'GREEN TO BLUE
        FileMoveMacinator(_CloudSyncFolder, _LocalItemsFolder, "F3Ext", False, "3", "2")
    End Sub

    Private Sub Grey2GreenBT_Click(sender As Object, e As EventArgs) Handles Grey2GreenBT.Click
        'GRAY TO GREEN WITH OPTIONAL BLUE
        FileMoveMacinator(_NewItemsFolder, _CloudSyncFolder, "F1Ext", False, "1", "3")
        If My.Settings.SettsIncBlue = True Then
            FileMoveMacinator(_NewItemsFolder, _LocalItemsFolder, "F1Ext", False, "1", "2")
        End If


    End Sub



    Private Sub IncludeBlueCB_CheckedChanged(sender As Object, e As EventArgs) Handles IncludeBlueCB.CheckedChanged
        If IncludeBlueCB.Checked Then
            My.Settings.SettsIncBlue = True
        Else
            My.Settings.SettsIncBlue = False
        End If
        My.Settings.Save()
    End Sub

    Private Sub ToggleSelCB_CheckedChanged(sender As Object, e As EventArgs) Handles ToggleSelCB.CheckedChanged
        For Each dgrow As DataGridViewRow In DGV1.SelectedRows
            dgrow.Cells("Sel").Value = ToggleSelCB.Checked
        Next
    End Sub

    Private Sub KillBatch_CheckedChanged(sender As Object, e As EventArgs) Handles KillBatch.CheckedChanged
        If KillBatch.Checked = True Then
            My.Settings.KillBatch = True
        Else
            My.Settings.KillBatch = False
        End If
        My.Settings.Save()
    End Sub

    Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
        AboutBox1.Show()
    End Sub

    Private Sub SystemsCB_SelectedIndexChanged(sender As Object, e As EventArgs) Handles SystemsCB.SelectedIndexChanged
        GameColumnTB.Items.Clear()
        Dim dd As New List(Of String)
        dd = SystemDatDict(SystemsCB.Text)
        GameColumnTB.Items.AddRange(dd.ToArray)
    End Sub


    Private Sub MatchRemBracketsChB_CheckedChanged(sender As Object, e As EventArgs) Handles MatchRemBracketsChB.CheckedChanged
        If MatchRemBracketsChB.Checked = True Then
            My.Settings.MatchRemBrackets = True
        Else
            My.Settings.MatchRemBrackets = False
        End If
        My.Settings.Save()
    End Sub


    Private Sub SaveAsCB_SelectedIndexChanged(sender As Object, e As EventArgs) Handles SaveAsCB.SelectedIndexChanged
        My.Settings.FileUseDBName = SaveAsCB.Text
        My.Settings.Save()
    End Sub



    Private Function FuzzyMatch(folder As Integer, tolerance As Integer, GameSearch As String) As String
        Debug.WriteLine("FUZZY SEARCH")

        Dim drow As DataGridViewRow = Nothing
        drow = DGV1.Rows(DGV1.SelectedCells(0).RowIndex)
        If drow Is Nothing Then Return -1
        ' Dim GameSearch As String = drow.Cells("GGameName").Value
        Dim FilenameSearch As String = drow.Cells("GPrimaryFilename").Value
        Debug.WriteLine("GameSerch: " & GameSearch)

        _GSMDS.Tables("Matches").Clear()

        FuzzyProg.Minimum = 0
        FuzzyProg.Maximum = _GSMDS.Tables("Files").Select("FolderID = " & folder).Count
        FuzzyProg.Value = 0



        For Each GFile As DataRow In _GSMDS.Tables("Files").Select("FolderID = " & folder)
            Debug.WriteLine("--------------------------------------")
            Debug.WriteLine("FileName: " & GFile.Item("Filename"))
            Debug.WriteLine("Name: " & GFile.Item("Name"))
            Dim matchOnFilename As Integer = Levenshtein(GFile.Item("Filename"), GameSearch)
            Dim matchOnGameName As Integer = Levenshtein(GFile.Item("Name"), GameSearch)

            Dim comp As StringComparison
            comp = StringComparison.OrdinalIgnoreCase
            Dim Issubstr As Boolean
            Issubstr = (GFile.Item("Filename").ToString).Contains(GameSearch, comp)
            If Issubstr Then
                matchOnFilename = 1
            End If
            If matchOnFilename < tolerance Or matchOnGameName < tolerance Or Issubstr Then
                Dim nrow As DataRow = _GSMDS.Tables("Matches").NewRow
                nrow.Item("DBName") = GameSearch
                nrow.Item("DBFilename") = FilenameSearch
                nrow.Item("ImgFilename") = GFile.Item("Filename")
                nrow.Item("ImgName") = GFile.Item("Name")
                nrow.Item("MatchOnFilename") = matchOnFilename
                nrow.Item("MatchOnGamename") = matchOnGameName
                nrow.Item("FileID") = GFile.Item("ID")
                _GSMDS.Tables("Matches").Rows.Add(nrow)
            End If
            FuzzyProg.Value += 1
        Next

        'return most likely
        Dim drGame As DataRow() = _GSMDS.Tables("Matches").Select("[MatchOnGamename] = MIN([MatchOnGamename])")
        Dim drFile As DataRow() = _GSMDS.Tables("Matches").Select("[MatchOnFilename] = MIN([MatchOnFilename])")
        Dim drFinal As DataRow() = Nothing

        If drFile.Length > 0 Then
            Debug.WriteLine("File, game: " & drFile(0).Item("MatchOnFilename") & ", " & drGame(0).Item("MatchOnGamename"))
            If CInt(drFile(0).Item("MatchOnFilename")) < CInt(drGame(0).Item("MatchOnGamename")) Then
                Debug.WriteLine("Filename more matched than gamename")
                drFinal = drFile
            Else
                Debug.WriteLine("Gamename more matched than Filename")
                drFinal = drGame
            End If
        End If

        If drFinal Is Nothing Then
            Return "No Matches"
        End If

        Return drFinal(0).Item("ImgFilename")

        Debug.WriteLine("--------------------------------------")
        Debug.WriteLine("FUZZY FINISHED")
    End Function

    Public Function Levenshtein(ByVal s As String, ByVal t As String) As Integer
        Dim n As Integer = s.Length
        Dim m As Integer = t.Length
        Dim d(n + 1, m + 1) As Integer

        If n = 0 Then
            Return m
        End If
        If m = 0 Then
            Return n
        End If

        Dim i As Integer
        Dim j As Integer

        For i = 0 To n
            d(i, 0) = i
        Next
        For j = 0 To m
            d(0, j) = j
        Next
        For i = 1 To n
            For j = 1 To m
                Dim cost As Integer
                If t(j - 1) = s(i - 1) Then
                    cost = 0
                Else
                    cost = 1
                End If
                d(i, j) = Math.Min(Math.Min(d(i - 1, j) + 1, d(i, j - 1) + 1), d(i - 1, j - 1) + cost)
            Next
        Next
        Return d(n, m)
    End Function

    Private Sub FuzzySearchBT_Click(sender As Object, e As EventArgs) Handles FuzzySearchBT.Click

        If SearchTypeTG.Tag = "web" Then
            ImgSearch(Nothing, Nothing)
            Return
        End If

        FuzzyProg.Visible = True
        FuzzySearchBT.Enabled = False
        FSearchActive = True

        Dim TopResult As String = FuzzyMatch(FuzzyFolderCB.SelectedValue,
                                             FuzzyNum.Value,
                                             FuzzyTB.Text)

        '  MsgBox(TopResult, MsgBoxStyle.Information)

        FuzzyProg.Visible = False
        FuzzySearchBT.Enabled = True
        FSearchActive = False

        FuzzyDGV.ClearSelection()

        If FuzzyDGV.Rows.Count > 0 Then
            FuzzyDGV.Sort(FuzzyDGV.Columns("MatchOnGamename"), ListSortDirection.Ascending)
            'FuzzyDGV.FirstDisplayedScrollingRowIndex = FuzzyDGV.Rows(0).Selected
            FuzzyDGV.Rows(0).Selected = True
            FuzzyDGV.CurrentCell = FuzzyDGV.Rows(0).Cells("ImgFilename")
        Else
            FuzzyImagePB.Image = My.Resources.no_image
        End If


        FuzzyAddBT.Enabled = True
        ' FuzzyFolderCB.Enabled = False
        MainDGVSplit.Panel2Collapsed = False

        OrigFolderLB.Text = FuzzyFolderCB.SelectedValue
        Select Case FuzzyFolderCB.SelectedValue
            Case 1
                SourceFolderIconPB.Image = My.Resources.gray_folder
            Case 2
                SourceFolderIconPB.Image = My.Resources.blue_folder
            Case 3
                SourceFolderIconPB.Image = My.Resources.greenfolder
        End Select

    End Sub

    Private Sub FuzzyDGV_RowEnter(sender As Object, e As DataGridViewCellEventArgs) Handles FuzzyDGV.RowEnter

        If e.RowIndex < 0 Then Return
        If FSearchActive = True Then Return

        Dim row As DataRow
        row = _GSMDS.Tables("Matches").Select("ID = " & FuzzyDGV.Rows(e.RowIndex).Cells("ID").Value)(0)


        Dim ImgFile1 As String = _NewItemsFolder & "\" & row.Item("ImgFilename")
        Dim ImgFile2 As String = _LocalItemsFolder & "\" & row.Item("ImgFilename")
        Dim ImgFile3 As String = _CloudSyncFolder & "\" & row.Item("ImgFilename")

        Dim ToUse As String = Nothing
        Select Case CInt(OrigFolderLB.Text)
            Case 1
                ToUse = ImgFile1
            Case 2
                ToUse = ImgFile2
            Case 3
                ToUse = ImgFile3
        End Select

        Debug.WriteLine("ToUse: " & ToUse)

        If IO.File.Exists(ToUse) Then
            FuzzyImagePB.Image = SafeImageFromFile(ToUse)
            StoredImage = SafeImageFromFile(ToUse)
            StoredImgPath = ToUse
        End If


    End Sub

    Public Shared Function SafeImageFromFile(path As String) As Image
        Using fs As New FileStream(path, FileMode.Open, FileAccess.Read)
            Dim img = Image.FromStream(fs)
            Return img
        End Using
    End Function

    Public Shared Function GetMimeType(i As Image) As String
        Dim imgguid = i.RawFormat.Guid
        For Each codec As ImageCodecInfo In ImageCodecInfo.GetImageDecoders()
            If codec.FormatID = imgguid Then
                Return codec.MimeType
            End If
        Next
        Return "image/unknown"
    End Function

    Private Sub FuzzyAddBT_Click(sender As Object, e As EventArgs) Handles FuzzyAddBT.Click
        Debug.WriteLine(vbCr & "Add Fuzzy/web Result")
        Dim folder2 As String
        Dim destination As String = Nothing
        Dim grow() As DataRow
        Dim filename As String
        Dim DestFile As String
        Dim ext As String

        Dim FinalOrig As String
        Dim FinalOut As String

        If SearchTypeTG.Tag = "web" Then

            If StoredImage Is Nothing Or Not (File.Exists(StoredImgPath)) Then
                log.Log_Data("ERROR: Tried to add web image, but no image stored. Return without action")
                Return
            End If

            grow = _MainDT.Select("GID= '" & FuzzyGameID.Text & "'")
            filename = Path.GetFileNameWithoutExtension(StoredImgPath)


            Debug.WriteLine("Filename intial: " & filename)
            Debug.WriteLine("SaveAs: " & My.Settings.FileUseDBName)
            ext = GetMimeType(StoredImage).Replace("image/", ".")
            If My.Settings.SaveAsPng = True Then
                ext = ".png"
            End If



            DestFile = Path.GetFileNameWithoutExtension(filename) & ext


            If My.Settings.FileUseDBName = "Database GameName" Then
                DestFile = SafeFilename(grow(0).Item("GGameName") & ext)
            ElseIf My.Settings.FileUseDBName = "Database Filename" Then
                DestFile = SafeFilename(grow(0).Item("GPrimaryFilename") & ext)
                If DestFile = "" Then
                    Debug.WriteLine("No database filename available - basing on database gamename")
                    DestFile = SafeFilename(grow(0).Item("GGameName") & ext)
                End If
            End If
            If UseFilenameTG.Tag = "true" Then
                DestFile = SafeFilename(FuzzyTB.Text & ext)
            End If
            Debug.WriteLine("Filename Final: " & DestFile)

            folder2 = FuzzyFolderCB.SelectedValue
            Dim fi As New IO.FileInfo(StoredImgPath)

            grow(0).Item("F" & folder2 & "FileName") = DestFile
            grow(0).Item("F" & folder2 & "Ext") = ext
            grow(0).Item("F" & folder2 & "Size") = Format(fi.Length / 1024, "##,##0.00")
            grow(0).Item("F" & folder2 & "Readonly?") = fi.IsReadOnly
            grow(0).Item("F" & folder2 & "DateLastSaved") = fi.LastWriteTime
            grow(0).Item("F" & folder2 & "DateCreated") = fi.CreationTime
            grow(0).Item("F" & folder2 & "DateAccessed") = fi.LastAccessTime
            grow(0).Item("F" & folder2 & "Width") = StoredImage.Width
            grow(0).Item("F" & folder2 & "Height") = StoredImage.Height
            grow(0).Item("F" & folder2 & "BitDepth") = StoredImage.PixelFormat
            grow(0).Item("F" & folder2 & "VPPi") = Format(StoredImage.VerticalResolution, "#.0")
            grow(0).Item("F" & folder2 & "HPPi") = Format(StoredImage.HorizontalResolution, "#.0")

            Dim destPB As New PictureBox
            Select Case folder2
                Case 1
                    destination = _NewItemsFolder
                    destPB = NewPB
                Case 2
                    destination = _LocalItemsFolder
                    destPB = LocalPB
                Case 3
                    destination = _CloudSyncFolder
                    destPB = CloudPB
            End Select

            'SAVE IMG
            Debug.WriteLine(">>> Save file routine")
            FinalOrig = StoredImgPath
            FinalOut = destination & "\" & DestFile

            If My.Settings.SaveAsPng Then
                Debug.WriteLine("save as png = true")
                If Path.GetExtension(FinalOrig) = "png" Then
                    Debug.WriteLine("file already png")
                Else
                    Debug.WriteLine("making new png file and updating vars")
                    FinalOrig = Path.GetDirectoryName(FinalOrig) & "\" &
                        Path.GetFileNameWithoutExtension(FinalOrig) & ".png"

                    ConvertImage(StoredImgPath, ImageFormat.Png, FinalOrig)

                    FinalOut = Path.GetDirectoryName(FinalOut) & "\" &
                        Path.GetFileNameWithoutExtension(FinalOut) & ".png"

                End If

            Else
                Debug.WriteLine("save as png = flase - preserve defaults")
            End If

            Debug.WriteLine("Final Orig: " & FinalOrig)
            Debug.WriteLine("Final Out: " & FinalOut)

            If File.Exists(FinalOut) And My.Settings.KillBatch = False Then
                Dim result As DialogResult = MessageBox.Show("The target of the copy already contains a file called: " & vbCr & vbCr & Path.GetFileName(FinalOut) & vbCr & vbCr & "Do you want to overwrite the existing file?",
                                                        "Overwrite file?", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation)
                If result = Windows.Forms.DialogResult.No Then Return
            End If

            destPB.Image = StoredImage

            My.Computer.FileSystem.CopyFile(
            FinalOrig,
            FinalOut,
            Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
            Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
            ' >>> SAVE IMG END

            Return

        End If

        ' =================== WEB SEARCH END ============================

        Dim mrow As DataRow
        mrow = _GSMDS.Tables("Matches").Select("ID = " &
                            FuzzyDGV.Rows(FuzzyDGV.SelectedCells(0).RowIndex).Cells("ID").Value)(0)

        filename = mrow.Item("ImgFilename")
        Debug.WriteLine("Filename intial: " & filename)
        DestFile = filename
        ext = Path.GetExtension(DestFile)
        grow = _MainDT.Select("GID= '" & FuzzyGameID.Text & "'")
        'If filename = "" Then filename = SafeFilename(grow(0).Item("GGamename"))
        If My.Settings.FileUseDBName = "Database GameName" Then
            Debug.WriteLine("SaveAs GameName")
            DestFile = SafeFilename(grow(0).Item("GGameName") & ext)
            Debug.WriteLine("Resulting DestFile: " & DestFile)
        ElseIf My.Settings.FileUseDBName = "Database Filename" Then
            DestFile = SafeFilename(grow(0).Item("GPrimaryFilename") & ext)
            If DestFile = "" Then
                Debug.WriteLine("No database filename available - basing on database gamename")
                DestFile = SafeFilename(grow(0).Item("GGameName") & ext)
            End If
        End If
        If UseFilenameTG.Tag = "true" Then
            DestFile = SafeFilename(FuzzyTB.Text & ext)
        End If

        Debug.WriteLine("Filename Final:" & DestFile)
        ' DestFile = SafeFilename(grow(0).Item("GPrimaryFilename") & ext)

        Dim frow As DataRow = _GSMDS.Tables("Files").Select("ID = " & mrow("FileID"))(0)

        folder2 = FuzzyFolderCB.SelectedValue

        'Now update DT - eeep
        '  Dim row() As DataRow = _MainDT.Select("GID= '" & GameID & "'")
        grow(0).Item("F" & folder2 & "FileName") = DestFile
        grow(0).Item("F" & folder2 & "Width") = frow.Item("Width")
        grow(0).Item("F" & folder2 & "Height") = frow.Item("Height")
        grow(0).Item("F" & folder2 & "Size") = frow.Item("FileSize")
        grow(0).Item("F" & folder2 & "Ext") = frow.Item("FileExtention")
        grow(0).Item("F" & folder2 & "BitDepth") = frow.Item("BitDepth")
        grow(0).Item("F" & folder2 & "VPPi") = frow.Item("VPpi")
        grow(0).Item("F" & folder2 & "HPPi") = frow.Item("HPpi")
        grow(0).Item("F" & folder2 & "Readonly?") = frow.Item("ReadOnly?")
        grow(0).Item("F" & folder2 & "DateLastSaved") = frow.Item("DateLastSaved")
        grow(0).Item("F" & folder2 & "DateCreated") = frow.Item("DateCreated")
        grow(0).Item("F" & folder2 & "DateAccessed") = frow.Item("DateAccessed")


        Dim origfolder As Integer = CInt(OrigFolderLB.Text)
        Dim source As String = Nothing

        Select Case origfolder
            Case 1
                source = _NewItemsFolder
            Case 2
                source = _LocalItemsFolder
            Case 3
                source = _CloudSyncFolder
        End Select

        Select Case folder2
            Case 1
                destination = _NewItemsFolder
                NewPB.Image = SafeImageFromFile(source & "\" & filename)
            Case 2
                destination = _LocalItemsFolder
                LocalPB.Image = SafeImageFromFile(source & "\" & filename)
            Case 3
                destination = _CloudSyncFolder
                CloudPB.Image = SafeImageFromFile(source & "\" & filename)
        End Select


        'Then Copy file
        'Use Folder search
        'If source & "\" & filename <> destination & "\" & DestFile Then
        '    My.Computer.FileSystem.CopyFile(
        '            source & "\" & filename,
        '            destination & "\" & DestFile,
        '            Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
        '            Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
        'End If

        'SAVE IMG
        Debug.WriteLine(">>> Save file routine")

        FinalOrig = source & "\" & filename
        FinalOut = destination & "\" & DestFile

        If My.Settings.SaveAsPng Then
            Debug.WriteLine("save as png = true")
            If Path.GetExtension(FinalOrig) = ".png" Then
                Debug.WriteLine("file already png")
            Else
                Debug.WriteLine("making new png file and updating vars")
                FinalOut = Path.GetDirectoryName(FinalOut) & "\" &
                    Path.GetFileNameWithoutExtension(FinalOut) & ".png"
                Debug.WriteLine("Final Orig: " & FinalOrig)
                Debug.WriteLine("Final Out: " & FinalOut)
                If File.Exists(FinalOut) And My.Settings.KillBatch = False Then
                    Dim result As DialogResult = MessageBox.Show("The target of the copy already contains a file called: " & vbCr & vbCr & Path.GetFileName(FinalOut) & vbCr & vbCr & "Do you want to overwrite the existing file?",
                                                            "Overwrite file?", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation)
                    If result = Windows.Forms.DialogResult.No Then Return
                End If
                ConvertImage(FinalOrig, ImageFormat.Png, FinalOut)
                Return 'as essentially file copied *1
            End If
        Else
            Debug.WriteLine("save as png = false - preserve defaults")
        End If

        Debug.WriteLine("Final Orig: " & FinalOrig)
        Debug.WriteLine("Final Out: " & FinalOut)

        If File.Exists(FinalOut) And My.Settings.KillBatch = False Then
            Dim result As DialogResult = MessageBox.Show("The target folder already contains a file called: " & vbCr & vbCr & Path.GetFileName(FinalOut) & vbCr & vbCr & "Do you want to overwrite the existing file?",
                                                    "Overwrite file?", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation)
            If result = Windows.Forms.DialogResult.No Then Return
        End If

        If FinalOrig = FinalOut Then
            Debug.WriteLine(">> Original and out the same - do not copy")
            Return ' don't copy file onto itself
        End If

        My.Computer.FileSystem.CopyFile(
        FinalOrig,
        FinalOut,
        Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
        Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
        ' >>> SAVE IMG END

        ' IF PLACE ANYTING BELOW HERE _ PAY ATTN TO RETURN @ *1 above


    End Sub



    Private Sub DGV1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGV1.CellContentClick

    End Sub

    Private Sub Button3_Click_1(sender As Object, e As EventArgs)
        Debug.WriteLine("Breaking...")
        Debug.WriteLine("Resumed...")
    End Sub


    Private Sub SearchPaneToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SearchPaneToolStripMenuItem.Click
        If SearchPaneToolStripMenuItem.Checked = True Then
            MainDGVSplit.Panel2Collapsed = False
        Else
            MainDGVSplit.Panel2Collapsed = True
        End If
    End Sub

    Private Sub ToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem1.Click
        If ToolStripMenuItem1.Checked = True Then
            DGV1.Columns("GPrimaryFilename").Visible = True
        Else
            DGV1.Columns("GPrimaryFilename").Visible = False

        End If
    End Sub

    Private Sub GrayFilenameToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles GrayFilenameToolStripMenuItem.Click

        If GrayFilenameToolStripMenuItem.Checked = True Then
            DGV1.Columns("F1FileName").Visible = True
        Else
            DGV1.Columns("F1FileName").Visible = False
        End If
    End Sub

    Private Sub BlueFilenameToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles BlueFilenameToolStripMenuItem.Click
        If BlueFilenameToolStripMenuItem.Checked = True Then
            DGV1.Columns("F2FileName").Visible = True
        Else
            DGV1.Columns("F2FileName").Visible = False
        End If

    End Sub

    Private Sub GreenFilenameToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles GreenFilenameToolStripMenuItem.Click
        If GreenFilenameToolStripMenuItem.Checked = True Then
            DGV1.Columns("F3FileName").Visible = True
        Else
            DGV1.Columns("F3FileName").Visible = False
        End If

    End Sub

    Private Sub ShowSelectedImageToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ShowSelectedImageToolStripMenuItem.Click
        NewPB_Click(NewPB, Nothing)
    End Sub

    Private Sub RemBracksDBGamenameChB_CheckedChanged(sender As Object, e As EventArgs) Handles RemBracksDBGamenameChB.CheckedChanged
        If RemBracksDBGamenameChB.Checked = True Then
            My.Settings.RemBracksGamename = True
        Else
            My.Settings.RemBracksGamename = False
        End If
        My.Settings.Save()
    End Sub


    Private Sub RemBracksDBFilenameChB_CheckedChanged(sender As Object, e As EventArgs) Handles RemBracksDBFilenameChB.CheckedChanged
        If RemBracksDBFilenameChB.Checked = True Then
            My.Settings.RemBracksFilename = True
        Else
            My.Settings.RemBracksFilename = False
        End If
        My.Settings.Save()
    End Sub

    Private Sub CompareFolderBT_Click(sender As Object, e As EventArgs) Handles CompareFolderBT.Click, LocalFolderBT.Click, CloudFolderBT.Click

        Select Case sender.name
            Case "CompareFolderBT"
                Process.Start(_NewItemsFolder)
            Case "LocalFolderBT"
                Process.Start(_LocalItemsFolder)
            Case "CloudFolderBT"
                Process.Start(_CloudSyncFolder)
        End Select
    End Sub

    Private Sub IncImgsMatchGnChB_CheckedChanged(sender As Object, e As EventArgs) Handles IncImgsMatchGnChB.CheckedChanged
        If IncImgsMatchGnChB.Checked = True Then
            My.Settings.IncImgsMatchGN = True
        Else
            My.Settings.IncImgsMatchGN = False
        End If
        My.Settings.Save()
    End Sub

    Private Sub CM1_Opening(sender As Object, e As CancelEventArgs) Handles CM1.Opening
        ToolStripMenuItem1.Checked = DGV1.Columns("GPrimaryFilename").Visible
        GrayFilenameToolStripMenuItem.Checked = DGV1.Columns("F1FileName").Visible
        BlueFilenameToolStripMenuItem.Checked = DGV1.Columns("F2FileName").Visible
        GreenFilenameToolStripMenuItem.Checked = DGV1.Columns("F3FileName").Visible
        DatabaseFilesafeGamenameToolStripMenuItem.Checked = DGV1.Columns("SafeGameName").Visible
    End Sub

    Private Sub DatabaseFilesafeGamenameToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DatabaseFilesafeGamenameToolStripMenuItem.Click

        If DatabaseFilesafeGamenameToolStripMenuItem.Checked = True Then
            DGV1.Columns("SafeGameName").Visible = True
        Else
            DGV1.Columns("SafeGameName").Visible = False
        End If
    End Sub

    Private Sub Button3_Click_2(sender As Object, e As EventArgs) Handles Button3.Click
        Dim x As Int32 = 1

    End Sub

    Private Sub UseFilenameTG_Click(sender As Object, e As EventArgs) Handles UseFilenameTG.Click
        If UseFilenameTG.Tag = "true" Then
            UseFilenameTG.Tag = "false"
            UseFilenameTG.BackColor = SystemColors.Control
        Else
            UseFilenameTG.Tag = "true"
            UseFilenameTG.BackColor = Color.LimeGreen
        End If
    End Sub

    Private Sub SearchTypeTG_BackgroundImageChanged(sender As Object, e As EventArgs) Handles SearchTypeTG.BackgroundImageChanged
        'Swap layouts when web/folder image changed
        Debug.WriteLine("search changed")
        Select Case SearchTypeTG.Tag
            Case "web"
                MainDGVSplit.Hide()
                WebPanel.Show()
            Case "folder"
                MainDGVSplit.Show()
                WebPanel.Hide()
        End Select
    End Sub


    Private Sub SearchTypeTG_Click(sender As Object, e As EventArgs) Handles SearchTypeTG.Click
        If SearchTypeTG.Tag = "folder" Then
            SearchTypeTG.Tag = "web"
            SearchTypeTG.BackgroundImage = My.Resources.icon_folder
            SourceFolderIconPB.Image = My.Resources.web
            FuzzyNum.Visible = False
            BkBT.Visible = True
            DLBT.Visible = True
            FuzzyFolderCB.Enabled = True
            FuzzyAddBT.Enabled = False
            FuzzyImagePB.Image = My.Resources.press_search
        Else
            SearchTypeTG.Tag = "folder"
            SearchTypeTG.BackgroundImage = My.Resources.web
            SourceFolderIconPB.Image = My.Resources.icon_folder
            FuzzyNum.Visible = True
            BkBT.Visible = False
            DLBT.Visible = False
            FuzzyAddBT.Enabled = False
            FuzzyImagePB.Image = My.Resources.press_search

        End If
    End Sub

    Private Sub WebPanel_VisibleChanged(sender As Object, e As EventArgs) Handles WebPanel.VisibleChanged
        If DGV1.SelectedCells.Count = 0 Then Return
        Dim selrow As DataGridViewRow = DGV1.Rows(DGV1.SelectedCells(0).RowIndex)
        Dim Gamename As String = selrow.Cells("GGameName").Value.ToString
        GameSearchTB.Text = Gamename
        FuzzyGameID.Text = selrow.Cells("GID").Value.ToString

        If WebPanel.Visible = True Then
            FuzzySearchBT_Click(Nothing, Nothing)
        End If


    End Sub

    Private Sub ImgSearch(sender As Object, e As EventArgs)
        Dim FinalURL As String = "https://www.google.co.uk/search?q=tomb+raider&as_st=y&hl=en&biw=1760&bih=885&source=lnms&tbm=isch&sa=X&ved=0CAgQ_AUoAmoVChMIja3Jzo6KxwIVh7oUCh3XPgD7#as_st=y&hl=en&tbm=isch&q=epic+fail"
        Dim SearchTerm As String = "Epic Fail"
        Dim SearchTools As String = ""

        If DirectCast(ImgSearchSizeCB.SelectedItem, KeyValuePair(Of String, String)).Value <> "" Then
            SearchTools = SearchTools & "," & DirectCast(ImgSearchSizeCB.SelectedItem, KeyValuePair(Of String, String)).Value
        End If
        If DirectCast(ImgSearchColorCB.SelectedItem, KeyValuePair(Of String, String)).Value <> "" Then
            SearchTools = SearchTools & "," & DirectCast(ImgSearchColorCB.SelectedItem, KeyValuePair(Of String, String)).Value
        End If
        If DirectCast(ImgSearchFormatCB.SelectedItem, KeyValuePair(Of String, String)).Value <> "" Then
            SearchTools = SearchTools & "," & DirectCast(ImgSearchFormatCB.SelectedItem, KeyValuePair(Of String, String)).Value
        End If
        If DirectCast(ImgSearchTypeCB.SelectedItem, KeyValuePair(Of String, String)).Value <> "" Then
            SearchTools = SearchTools & "," & DirectCast(ImgSearchTypeCB.SelectedItem, KeyValuePair(Of String, String)).Value
        End If


        SearchTerm = RTrim(FuzzyTB.Text) & " " & ImgSearchTermCB.Text
        SearchTerm = SearchTerm.Replace(" ", "+")
        FinalURL = "https://www.google.co.uk/search?hl=en&site=imghp&tbm=isch" &
             "&q=" & SearchTerm & "&tbs=imgo:1" &
             SearchTools

        Debug.WriteLine(">>> FINAL GOOGLE URL: " & FinalURL)

        _ImgSearchWebBrowser.Navigate(FinalURL, False)
    End Sub

    Private Sub webBrowser1_NewWindow(sender As Object, e As CancelEventArgs) Handles _ImgSearchWebBrowser.NewWindow
        _ImgSearchWebBrowser.Navigate(_ImgSearchWebBrowser.StatusText)
        e.Cancel = True
    End Sub

    Public Sub ImgGet()

        Dim DLError As Boolean = False
        Dim ErrorList As List(Of String) = Nothing

        Dim wcObj As New System.Net.WebClient() 'Create New Web Client Object
        Try
            hecImages = _ImgSearchWebBrowser.Document.GetElementsByTagName("img") 'Browse Through HTML Tags
        Catch ex As Exception
            Return
        End Try
        Dim ImgDL As New ImageSave
        ImgDL.MakePNG = My.Settings.SaveAsPng
        ImgDL.SafeFilename = SafeFilename(GameSearchTB.Text)
        ImgDL.ShowDialog()

        Debug.WriteLine("Image return: " & StoredImgPath)
        FuzzyImagePB.Image = StoredImage
        FuzzyAddBT.Enabled = True
    End Sub

    Private Sub BkBT_Click(sender As Object, e As EventArgs) Handles BkBT.Click
        _ImgSearchWebBrowser.GoBack()
    End Sub

    Private Sub DLBT_Click(sender As Object, e As EventArgs) Handles DLBT.Click
        ImgGet()
    End Sub

    Public Sub ConvertImage(ByVal Filename As String, ByVal DesiredFormat As System.Drawing.Imaging.ImageFormat,
                                 ByVal NewFilename As String)

        Debug.WriteLine(">>> CONVERT IMAGE SUB")
        ' Takes a filename and saves the file in a new format
        Try
            Dim imgFile As New Bitmap(SafeImageFromFile(Filename))

            If File.Exists(NewFilename) Then
                File.Delete(NewFilename)
            End If

            imgFile.Save(NewFilename, DesiredFormat)
        Catch ex As Exception
            log.Log_Error("Whilst converting image to png: " & ex.Message & vbCr & ex.StackTrace)
        End Try
    End Sub


    Private Sub SaveAsPNGChB_CheckedChanged(sender As Object, e As EventArgs) Handles SaveAsPNGChB.CheckedChanged
        If sender.checked = True Then
            My.Settings.SaveAsPng = True
        Else
            My.Settings.SaveAsPng = False
        End If
        My.Settings.Save()
    End Sub


    Private Sub SearchBT_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub GameSearchCB_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GameSearchCB.SelectedIndexChanged
        Debug.WriteLine("Game Search: " & sender.text)
        Debug.WriteLine("Game ID: " & GameSearchCB.SelectedValue)
        Dim Gid As Integer = GameSearchCB.SelectedValue

        For Each drow As DataGridViewRow In DGV1.Rows
            If drow.Cells("GID").Value = Gid Then
                DGV1.ClearSelection()
                DGV1.Rows(drow.Index).Selected = True
                DGV1.FirstDisplayedScrollingRowIndex = drow.Index
                FuzzyTB.Text = SafeFilename(drow.Cells("GGameName").Value)
                Exit For
            End If
        Next

    End Sub

    Private Sub EditImgBT_Click(sender As Object, e As EventArgs) Handles EditImgBT.Click
        If StoredImage Is Nothing Or StoredImgPath = Nothing Then
            MsgBox("No search image loaded", MsgBoxStyle.Information, "Edit Search Image")
            Return
        End If
        If Path.GetDirectoryName(StoredImgPath) <> Path.GetTempPath & "GameSetMatch" And
            My.Settings.KillBatch = False Then
            Dim result As DialogResult = MessageBox.Show("You are editing one of the folders' image folders directly. Do you want to continue?",
                                        "Edit Folder file?", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation)
            If result = Windows.Forms.DialogResult.No Then Return
        End If

        Dim startInfo As New ProcessStartInfo
        startInfo.FileName = My.Settings.DefImageEditor
        startInfo.Arguments = """" & StoredImgPath & """"
        Process.Start(startInfo)
    End Sub



    Private Sub RefreshImgBT_Click(sender As Object, e As EventArgs) Handles RefreshImgBT.Click
        If StoredImage Is Nothing Then Return
        Dim newimg As Image = SafeImageFromFile(StoredImgPath)
        FuzzyImagePB.Image = newimg
        StoredImage = newimg
    End Sub

    Private Sub DefImageEditorBT_Click(sender As Object, e As EventArgs) Handles DefImageEditorBT.Click
        With OFD1
            .Title = "Choose the executable of your default image editor."
            .Filter = "EXE|*.exe|All Files|*.*"
            Try
                .InitialDirectory = Path.GetDirectoryName(DefImageEditorTB.Text)
                .FileName = Path.GetFileName(DefImageEditorTB.Text)
            Catch
                .InitialDirectory = My.Computer.FileSystem.SpecialDirectories.ProgramFiles
            End Try
        End With

        If OFD1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Try
                DefImageEditorTB.Text = OFD1.FileName
                My.Settings.DefImageEditor = OFD1.FileName
                My.Settings.Save()
            Catch

            End Try
        End If
    End Sub

    Private Sub FullFileDetailsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles FullFileDetailsToolStripMenuItem.Click
        If FullFileDetailsToolStripMenuItem.Checked Then
            My.Settings.ShowFullInfo = True
            If DGV1.Columns.Contains("F1BitDepth") Then
                DGV1.Columns("F1BitDepth").Visible = True
                DGV1.Columns("F1VPPi").Visible = True
                DGV1.Columns("F1HPPi").Visible = True
                DGV1.Columns("F1Readonly?").Visible = True
                DGV1.Columns("F1DateLastSaved").Visible = True
                DGV1.Columns("F1DateCreated").Visible = True
                DGV1.Columns("F1DateAccessed").Visible = True
                DGV1.Columns("F2BitDepth").Visible = True
                DGV1.Columns("F2VPPi").Visible = True
                DGV1.Columns("F2HPPi").Visible = True
                DGV1.Columns("F2Readonly?").Visible = True
                DGV1.Columns("F2DateLastSaved").Visible = True
                DGV1.Columns("F2DateCreated").Visible = True
                DGV1.Columns("F2DateAccessed").Visible = True
                DGV1.Columns("F3BitDepth").Visible = True
                DGV1.Columns("F3VPPi").Visible = True
                DGV1.Columns("F3HPPi").Visible = True
                DGV1.Columns("F3Readonly?").Visible = True
                DGV1.Columns("F3DateLastSaved").Visible = True
                DGV1.Columns("F3DateCreated").Visible = True
                DGV1.Columns("F3DateAccessed").Visible = True
            End If
        Else
            My.Settings.ShowFullInfo = False
            If DGV1.Columns.Contains("F1BitDepth") Then
                DGV1.Columns("F1BitDepth").Visible = False
                DGV1.Columns("F1VPPi").Visible = False
                DGV1.Columns("F1HPPi").Visible = False
                DGV1.Columns("F1Readonly?").Visible = False
                DGV1.Columns("F1DateLastSaved").Visible = False
                DGV1.Columns("F1DateCreated").Visible = False
                DGV1.Columns("F1DateAccessed").Visible = False
                DGV1.Columns("F2BitDepth").Visible = False
                DGV1.Columns("F2VPPi").Visible = False
                DGV1.Columns("F2HPPi").Visible = False
                DGV1.Columns("F2Readonly?").Visible = False
                DGV1.Columns("F2DateLastSaved").Visible = False
                DGV1.Columns("F2DateCreated").Visible = False
                DGV1.Columns("F2DateAccessed").Visible = False
                DGV1.Columns("F3BitDepth").Visible = False
                DGV1.Columns("F3VPPi").Visible = False
                DGV1.Columns("F3HPPi").Visible = False
                DGV1.Columns("F3Readonly?").Visible = False
                DGV1.Columns("F3DateLastSaved").Visible = False
                DGV1.Columns("F3DateCreated").Visible = False
                DGV1.Columns("F3DateAccessed").Visible = False
            End If

        End If
    End Sub


    Private Sub HLColPB_Click(sender As Object, e As EventArgs) Handles HLColPB.Click
        With CD1
            .AllowFullOpen = True
            .AnyColor = True
            .Color = My.Settings.HighlightCol
            .FullOpen = True
            .SolidColorOnly = True
        End With
        Dim result As DialogResult = CD1.ShowDialog()
        My.Settings.HighlightCol = CD1.Color
        HighlighCol = CD1.Color
        HLColPB.BackColor = CD1.Color
    End Sub

    Private Sub Button1_Click_2(sender As Object, e As EventArgs) Handles Button1.Click
        Process.Start(_LogFile)
    End Sub

    Private Sub ChangelogBT_Click(sender As Object, e As EventArgs) Handles ChangelogBT.Click
        If File.Exists(Path.GetTempPath & "/changelog.txt") Then
            File.Delete(Path.GetTempPath & "/changelog.txt")
        End If
        File.WriteAllText(Path.GetTempPath & "/changelog.txt", My.Resources.Changelog)
        Threading.Thread.Sleep(500)
        Process.Start(Path.GetTempPath & "/changelog.txt")
    End Sub

 
    Private Sub BUDbBT_Click(sender As Object, e As EventArgs) Handles BUDbBT.Click
        Dim filename As String = Nothing
        With SFD
            .AddExtension = True
            .DefaultExt = ".xml"
            .FileName = "GameSetMatch.xml"
            .InitialDirectory = SpecialFolder.MyDocuments
            .OverwritePrompt = True
            .Title = "Save database backup as...."
            .ValidateNames = True
        End With

        Dim result As DialogResult = SFD.ShowDialog()
        If result = Windows.Forms.DialogResult.OK Then
            FileName = SFD.FileName
        Else
            Return
        End If

        My.Computer.FileSystem.CopyFile(
            _KeepDSFile,
            filename,
            Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
            Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)

    End Sub

    Private Sub RestoreDbBT_Click(sender As Object, e As EventArgs) Handles RestoreDbBT.Click

        Dim result As DialogResult = MessageBox.Show("The diaolgue opens in the database backups folder, but you can navigate elsewhere. Once you have chosen a file to restore to, the application will close as it requires a restart. Are you sure you wish to restore the database to another version?",
                                        "Restore Database?", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation)
        If result = Windows.Forms.DialogResult.No Then Return


        Dim source As String = Nothing
        With OFD1
            .Title = "Choose the database xml to restore to...."
            .Filter = "XML|*.xml|All Files|*.*"
            Try
                .InitialDirectory = Environment.GetFolderPath(SpecialFolder.ApplicationData) & "\GameSetMatch\DbBackup"
            Catch
                .InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
                .FileName = "GameSetMatch.xml"
            End Try
        End With

        If OFD1.ShowDialog = Windows.Forms.DialogResult.OK Then
            source = OFD1.FileName
        End If
        If File.Exists(source) Then
            Try
                My.Computer.FileSystem.CopyFile(
                      source,
                      _KeepDSFile,
                      Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
                      Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
                log.Log_Data("Database restored to previous version.")
            Catch ex As Exception
                log.Log_Data("Error whilst copying database backup file")
            End Try

        Else
            log.Log_Data("DBBackup file doesn't exist. Aborting")
        End If

        DatabaseChanged = True

        MsgBox("Database successfully restored. The application will now quit as a restart is needed to restore the database to another version.", MsgBoxStyle.Information, "Application restart")
        Me.Close()

    End Sub

    Private Sub SourceFolderIconPB_Click(sender As Object, e As EventArgs) Handles SourceFolderIconPB.Click

    End Sub
End Class





